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.
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
andtyped
are lowercase letters.
Solution: Two Pointers
Time complexity: O(n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Author: Huahua, 0 ms class Solution { public: bool isLongPressedName(string name, string typed) { int i = 0; int j = 0; while (i < name.size() && j < typed.size()) { if (name[i] == typed[j]) { ++i; ++j; } else if (j > 0 && typed[j] == typed[j - 1]) { ++j; } else { return false; } } while (j < typed.size() && typed[j] == typed[j - 1]) ++j; return i == name.size() && j == typed.size(); } }; |
C++ / Iterator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Author: Huahua class Solution { public: bool isLongPressedName(string name, string typed) { auto it1 = begin(name); auto it2 = begin(typed); while (it1 != end(name) && it2 != end(typed)) { if (*it1 == *it2) { ++it1; ++it2; } else if (it2 != begin(typed) && *it2 == *prev(it2)) { ++it2; } else { return false; } } while (it2 != end(typed) && *it2 == *prev(it2)) ++it2; return it1 == end(name) && it2 == end(typed); } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment