925. Long Pressed Name(Leetcode每日一题-2020.10.21)

it2025-02-16  5

Problem

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.

Constraints:

1 <= name.length <= 10001 <= typed.length <= 1000The characters of name and typed are lowercase letters.

Example1

Input: name = “alex”, typed = “aaleex” Output: true Explanation: ‘a’ and ‘e’ in ‘alex’ were long pressed.

Example2

Input: name = “saeed”, typed = “ssaaedd” Output: false Explanation: ‘e’ must have been pressed twice, but it wasn’t in the typed output.

Example3

Input: name = “leelee”, typed = “lleeelee” Output: true

Example4

Input: name = “laiden”, typed = “laiden” Output: true Explanation: It’s not necessary to long press any character.

Solution

顺序遍历name和typed,如果当前字符相同,就把指针都向后移动,否则如果typed与之前一样,就将typed的指针向后移动。

class Solution { public: bool isLongPressedName(string name, string typed) { int i = 0; int j = 0; if(name[0] != typed[0]) return false; while(i < name.length() && j < typed.length()) { if(name[i] == typed[j]) { ++i; ++j; } else { while(name[i] != typed[j] && typed[j] == typed[j-1] ) { ++j; } if(name[i] != typed[j]) return false; } } cout <<i <<" "<<j<<endl; if(i == name.length()) { while(j < typed.length()-1) { if(typed[j] != typed[j+1]) return false; ++j; } return true; } else return false; } };
最新回复(0)