925 Long Pressed Name 長(zhǎng)按鍵入
Description:
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:
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 wasn't in the typed output.
Example 3:
Input: name = "leelee", typed = "lleeelee"
Output: true
Example 4:
Input: name = "laiden", typed = "laiden"
Output: true
Explanation: It's not necessary to long press any character.
Note:
name.length <= 1000
typed.length <= 1000
The characters of name and typed are lowercase letters.
題目描述:
你的朋友正在使用鍵盤(pán)輸入他的名字 name。偶爾,在鍵入字符 c 時(shí),按鍵可能會(huì)被長(zhǎng)按,而字符可能被輸入 1 次或多次。
你將會(huì)檢查鍵盤(pán)輸入的字符 typed。如果它對(duì)應(yīng)的可能是你的朋友的名字(其中一些字符可能被長(zhǎng)按),那么就返回 True。
示例 :
示例 1:
輸入:name = "alex", typed = "aaleex"
輸出:true
解釋:'alex' 中的 'a' 和 'e' 被長(zhǎng)按。
示例 2:
輸入:name = "saeed", typed = "ssaaedd"
輸出:false
解釋:'e' 一定需要被鍵入兩次,但在 typed 的輸出中不是這樣。
示例 3:
輸入:name = "leelee", typed = "lleeelee"
輸出:true
示例 4:
輸入:name = "laiden", typed = "laiden"
輸出:true
解釋:長(zhǎng)按名字中的字符并不是必要的。
提示:
name.length <= 1000
typed.length <= 1000
name 和 typed 的字符都是小寫(xiě)字母。
思路:
雙指針?lè)?br>
注意!
typed的末尾可能和name的末尾不相等
如alex和alexfowefoiwofnewo
時(shí)間復(fù)雜度O(n), 空間復(fù)雜度O(1)
代碼:
C++:
class Solution
{
public:
bool isLongPressedName(string name, string typed)
{
if (name.size() > typed.size()) return false;
int i = 0, j = 0;
while (i < name.size() and j < typed.size())
{
if (name[i] == typed[j])
{
i++;
j++;
}
else if (j > 0 and typed[j] == typed[j - 1]) j++;
else return false;
}
if (i == name.size())
{
while (j < typed.size())
{
if (typed[j] != name[i - 1]) return false;
j++;
}
}
else return false;
return true;
}
};
Java:
class Solution {
public boolean isLongPressedName(String name, String typed) {
if (name.length() > typed.length()) return false;
int i = 0, j = 0;
while (i < name.length() && j < typed.length()) {
if (name.charAt(i) == typed.charAt(j)) {
i++;
j++;
}
else if (j > 0 && typed.charAt(j) == typed.charAt(j - 1)) j++;
else return false;
}
if (i == name.length()) {
while (j < typed.length()) {
if (typed.charAt(j) != name.charAt(i - 1)) return false;
j++;
}
} else return false;
return true;
}
}
Python:
class Solution:
def isLongPressedName(self, name: str, typed: str) -> bool:
if len(name) > len(typed):
return False
i, j = 0, 0
while i < len(name) and j < len(typed):
if name[i] == typed[j]:
i += 1
j += 1
elif j > 0 and typed[j] == typed[j - 1]:
j += 1
else:
return False;
if i == len(name):
while j < len(typed):
if typed[j] != name[-1]:
return False
j += 1
else:
return False
return True