原题地址(简单)

方法1—双指针

思路

索然无味的一题。。。
要留心的一种情况就是 name="la",typed="l"name="l", typed="la" 这两种情况。

代码

  1. class Solution {
  2. public:
  3. bool isLongPressedName(string name, string typed) {
  4. int p = 0, q = 0;
  5. int len1 = name.size(), len2 = typed.size();
  6. while(p < len1 && q < len2) {
  7. if(name[p] == typed[q]){
  8. p++;
  9. q++;
  10. int sum1 = 0, sum2 = 0;
  11. while(p < len1 && name[p] == name[p-1]){
  12. sum1++;
  13. p++;
  14. }
  15. while(q < len2 && typed[q] == typed[q-1]){
  16. sum2++;
  17. q++;
  18. }
  19. if(sum1 <= sum2) continue;
  20. else return false;
  21. }
  22. else return false;
  23. }
  24. if(p >= len1 && q >= len2)
  25. return true;
  26. else return false;
  27. }
  28. };

官方题解

  1. class Solution {
  2. public:
  3. bool isLongPressedName(string name, string typed) {
  4. int i = 0, j = 0;
  5. while (j < typed.length()) {
  6. if (i < name.length() && name[i] == typed[j]) {
  7. i++;
  8. j++;
  9. } else if (j > 0 && typed[j] == typed[j - 1]) {
  10. j++;
  11. } else {
  12. return false;
  13. }
  14. }
  15. return i == name.length();
  16. }
  17. };
  18. 作者:LeetCode-Solution
  19. 链接:https://leetcode-cn.com/problems/long-pressed-name/solution/chang-an-jian-ru-by-leetcode-solution/
  20. 来源:力扣(LeetCode
  21. 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

时空复杂度

O(M+N) O(1)