题目:LeetCode 925.长按键入
问题:
你的朋友正在使用键盘输入他的名字 name。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能被输入 1 次或多次。
你将会检查键盘输入的字符 typed。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/long-pressed-name 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码
bool
isLongPressedName(char * name
, char * typed
) {
int NameLength
= strlen(name
);
int TypeLength
= strlen(typed
);
if (NameLength
> TypeLength
) {
return false
;
}
int name_location
= 0;
int typed_location
= 0;
while (typed_location
< TypeLength
) {
if (name_location
< NameLength
&& name
[name_location
] == typed
[typed_location
]) {
name_location
++;
typed_location
++;
}
else if (typed_location
> 0 && typed
[typed_location
] == typed
[typed_location
- 1]) {
typed_location
++;
}
else
{
return false
;
}
}
return NameLength
== name_location
;
}
思路:
1. 先比较name和typed的长度,如果name比typed长,返回false
2. 从第一个字符开始进行比较
相等: 两个指针都向后移;
不相等:判断 typed 当前指向的字符与前一个字符是否相同
(如果是第一个字符不相等,返回false)
相同:typed 指针向后移
不相同: 返回
false
3. 当typed指针指向最后一个字符后退出循环后:
返回值由name的指针是否到达最后一个字符决定。