你的朋友正在使用键盘输入他的名字 name。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能被输入 1 次或多次。
你将会检查键盘输入的字符 typed。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True。
示例 1:
输入:name = “alex”, typed = “aaleex”
输出:true
解释:‘alex’ 中的 ‘a’ 和 ‘e’ 被长按。
示例 2:
输入:name = “saeed”, typed = “ssaaedd”
输出:false
解释:‘e’ 一定需要被键入两次,但在 typed 的输出中不是这样。
示例 3:
输入:name = “leelee”, typed = “lleeelee”
输出:true
示例 4:
输入:name = “laiden”, typed = “laiden”
输出:true
解释:长按名字中的字符并不是必要的。
提示:
name.length <= 1000
typed.length <= 1000
name 和 typed 的字符都是小写字母。
解题思路:
这道题目说是简单题,其实复杂得很,判断条件相当多,当然确定好思路也就顺理成章了。
- 首先分析一下可知,在输入按键的时候,第一个按键一定要相同,不同肯定不对。
- 其次,在遍历name时候发现对应的typed不一样,那就遍历typed的相同字符直到一样,还是不一样就返回false。
- 如果遍历完typed发现name没遍历完,说明肯定有错,返回false。
- 最后如果name遍历完了,发现typed没遍历完,那么遍历typed的最后元素,如果有不同字符也返回false。
代码如下:
class Solution {
public:
bool isLongPressedName(string name, string typed) {
bool flag = true;
int index = 0;
if(name[0] != typed[0]){
return false;
}
for(int i = 0; i < name.length(); i ++){
if(index < typed.length()){
if(name[i] == typed[index]){
index ++;
continue;
}
while(typed[index + 1] == typed[index] && (index + 1) < typed.length()){
index ++;
}
index ++;
if(typed[index] != name[i]){
return false;
}
index ++;
}
else{
return false;
}
}
if(index < typed.length()){
while(typed[index + 1] == typed[index] && index + 1 < typed.length()){
index ++;
}
index ++;
}
if(index == typed.length()){
return flag;
}
return false;
}
};
/*作者:heroding
链接:https://leetcode-cn.com/problems/long-pressed-name/solution/zhi-xing-yong-shi-ji-bai-100si-lu-zui-qing-xi-de-d/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/