双指针的问题,如果当前两个指针对应的字符一样,我们统计各自连续字符的数量。如果typed的数量大于等于name的,那么我们继续。当且仅当出现以下情况的时候我们return false:
- 两个指针对应的字符不一样
- typed的对应连续字符的数量小于name的数量
- 其中一个字符串到了末尾,另一个还没到
时间复杂度O(N),常数空间。代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool isLongPressedName(string name, string typed) { | |
int len1 = name.size(), len2 = typed.size(), i = 0, j = 0; | |
while(i < len1 && j < len2) | |
{ | |
if(name[i] != typed[j])return false; | |
int cnt1 = 0, cnt2 = 0; | |
char c = name[i]; | |
while(i < len1 && name[i] == c){++i; ++cnt1;} | |
while(j < len2 && typed[j] == c){++j; ++cnt2;} | |
if(cnt1 > cnt2)return false; | |
} | |
return i >= len1 && j >= len2; | |
} | |
}; |
No comments:
Post a Comment