leetcode-master/problems/0925.长按键入.md

62 lines
2.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 思路
这道题目一看以为是哈希,仔细一看不行,要有顺序。
所以模拟同时遍历两个数组,进行对比就可以了。
对比的时候需要一下几点:
* name[i] 和 typed[j]相同则i++j++ (继续向后对比)
* name[i] 和 typed[j]不相同
* 看是不是第一位就不相同了也就是j如果等于0那么直接返回false
* 不是第一位不相同就让j跨越重复项移动到重复项之后的位置再次比较name[i] 和typed[j]
* 如果 name[i] 和 typed[j]相同则i++j++ (继续向后对比)
* 不相同返回false
* 对比完之后有两种情况
* name没有匹配完例如name:"pyplrzzzzdsfa" type:"ppyypllr"
* type没有匹配完例如name:"alex" type:"alexxrrrrssda"
动画如下:
<img src='../video/925.长按键入.gif' width=600> </img></div>
上面的逻辑想清楚了不难写出如下C++代码:
```
class Solution {
public:
bool isLongPressedName(string name, string typed) {
int i = 0, j = 0;
while (i < name.size() && j < typed.size()) {
if (name[i] == typed[j]) { // 相同则同时向后匹配
j++; i++;
} else { // 不相同
if (j == 0) return false; // 如果是第一位就不相同直接返回false
// j跨越重复项向后移动同时防止j越界
while(j < typed.size() && typed[j] == typed[j - 1]) j++;
if (name[i] == typed[j]) { // j跨越重复项之后再次和name[i]匹配
j++; i++; // 相同则同时向后匹配
}
else return false;
}
}
// 说明name没有匹配完例如 name:"pyplrzzzzdsfa" type:"ppyypllr"
if (i < name.size()) return false;
// 说明type没有匹配完例如 name:"alex" type:"alexxrrrrssda"
while (j < typed.size()) {
if (typed[j] == typed[j - 1]) j++;
else return false;
}
return true;
}
};
```
时间复杂度O(n)
空间复杂度O(1)
> 更多算法干货文章持续更新可以微信搜索「代码随想录」第一时间围观关注后回复「Java」「C++」 「python」「简历模板」「数据结构与算法」等等就可以获得我多年整理的学习资料。