LeetCode 925 Long Pressed Name

it2024-11-05  17

LeetCode 925 Long Pressed Name

题目链接

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 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.

这题比较扣细节,我是这么考虑的,每次选字符串的第一个字符,然后分别取出所有该字符的数量为 c n t 1 cnt1 cnt1 c n t 2 cnt2 cnt2,显然如果不是长按输入有三种情况:

字符不相同 c n t 1 > c n t 2 cnt1>cnt2 cnt1>cnt2两个字符串中有且仅有一个长度为 0 0 0

AC代码如下:

class Solution { public: bool isLongPressedName(string name, string typed) { while(name.size()&&typed.size()){ int cnt1=0,cnt2=0; char a=name[0]; while(name[0]==a) name.erase(name.begin()),cnt1++; char b=typed[0]; while(typed[0]==b) typed.erase(typed.begin()),cnt2++; if(a!=b||cnt1>cnt2||(name.size()*typed.size()==0&&name.size()+typed.size())) return 0; } return 1; } };
最新回复(0)