Your friend is typing his name
into a keyboard. Sometimes, when typing a character c
, the key might get long pressed, and the character will be typed 1 or more times.
You examine the typed
characters of the keyboard. Return True
if it is possible that it was your friends name, with some characters (possibly none) being long pressed.
Example 1:
Input: name = "alex", typed = "aaleex" Output: true Explanation: 'a' and 'e' in 'alex' were long pressed.
Example 2:
Input: name = "saeed", typed = "ssaaedd" Output: false Explanation: 'e' must have been pressed twice, but it was not in the typed output.
Constraints:
1 <= name.length, typed.length <= 1000
-
name
andtyped
consist of only lowercase English letters.
这题给了两个string,其中一个是原字符串,另一个是原字符串中某个字符可能连续出现了多次,要求第二个字符串符不符合这个条件。
嗯,第一反应其实就是two pointers拿两个pointer分别指向name和typed,判断是否一样,以及如果typed里这个字符连续出现多次就pointer++跳过。于是显然忘了name里也可能出现两个一样的字符连在一起的情况。然后就开始各种if写了起来,而且因为p++和p + 1的时候特别容易出现边界条件的问题,所以就越写越乱,思路也乱代码也乱,就是一团糟了。
于是一气之下决定重写,用同样的方法计算每个连续的字符分别在两个string里出现了几次,如果name里出现的次数少于typed里出现的次数那就显然不符合条件。最后两个都会在字符串末尾结束,如果没有同时在字符串末尾结束的话就说明不符合条件了。这样写出来的代码非常直观而且不容易出错,没什么corner cases,喜欢。但是效率的话打败了70%,其实也还行了,对于自己硬写出来的已经满意了。
观察了一下大家的做法,其实也都大差不差,而且很多也都挺复杂,corner case太烦了,遂放弃,满足于自己写的了。文章来源:https://www.toymoban.com/news/detail-684438.html
class Solution {
public boolean isLongPressedName(String name, String typed) {
int p1 = 0;
int p2 = 0;
while (p1 < name.length() && p2 < typed.length()) {
if (name.charAt(p1) != typed.charAt(p2)) {
return false;
}
int typedRepeat = 0;
while (p2 < typed.length() - 1 && typed.charAt(p2) == typed.charAt(p2 + 1)) {
p2++;
typedRepeat++;
}
int nameRepeat = 0;
while (p1 < name.length() - 1 && name.charAt(p1) == name.charAt(p1 + 1)) {
p1++;
nameRepeat++;
}
if (typedRepeat < nameRepeat) {
return false;
}
p1++;
p2++;
}
return p1 == name.length() && p2 == typed.length();
}
}
其实这个解法还挺有意思的,计算了两个字符串之间的差,看代码也没啥太多corner case:LeetCode - The World's Leading Online Programming Learning Platform文章来源地址https://www.toymoban.com/news/detail-684438.html
到了这里,关于LeetCode 925. Long Pressed Name的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!