原题地址(简单)
方法1—双指针
思路
索然无味的一题。。。
要留心的一种情况就是 name="la",typed="l"
和 name="l", typed="la"
这两种情况。
代码
class Solution {
public:
bool isLongPressedName(string name, string typed) {
int p = 0, q = 0;
int len1 = name.size(), len2 = typed.size();
while(p < len1 && q < len2) {
if(name[p] == typed[q]){
p++;
q++;
int sum1 = 0, sum2 = 0;
while(p < len1 && name[p] == name[p-1]){
sum1++;
p++;
}
while(q < len2 && typed[q] == typed[q-1]){
sum2++;
q++;
}
if(sum1 <= sum2) continue;
else return false;
}
else return false;
}
if(p >= len1 && q >= len2)
return true;
else return false;
}
};
官方题解
class Solution {
public:
bool isLongPressedName(string name, string typed) {
int i = 0, j = 0;
while (j < typed.length()) {
if (i < name.length() && name[i] == typed[j]) {
i++;
j++;
} else if (j > 0 && typed[j] == typed[j - 1]) {
j++;
} else {
return false;
}
}
return i == name.length();
}
};
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/long-pressed-name/solution/chang-an-jian-ru-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
时空复杂度
O(M+N)
O(1)