leetcode 925. 长按键入

it2024-04-22  61

leetcode 925. 长按键入

题目详情

题目链接 你的朋友正在使用键盘输入他的名字 name。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能被输入 1 次或多次。 你将会检查键盘输入的字符 typed。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True。

示例 1: 输入:name = “alex”, typed = “aaleex” 输出:true 解释:‘alex’ 中的 ‘a’ 和 ‘e’ 被长按。示例 2: 输入:name = “saeed”, typed = “ssaaedd” 输出:false 解释:‘e’ 一定需要被键入两次,但在 typed 的输出中不是这样。示例 3: 输入:name = “leelee”, typed = “lleeelee” 输出:true示例 4: 输入:name = “laiden”, typed = “laiden” 输出:true 解释:长按名字中的字符并不是必要的。提示: name.length <= 1000 typed.length <= 1000 name 和 typed 的字符都是小写字母。

我的代码

class Solution { public: bool isLongPressedName(string name, string typed) { int n1 = name.size(), n2 = typed.size(); if (n1 > n2) { return false; } if (n1 == n2) { return name == typed; } if (n1 < 1) { return false; } if (name[0] != typed[0]) { return false; } int pos1 = 1, pos2 = 1; while (pos1 < n1) { if (name[pos1] == typed[pos2]) { pos1++; pos2++; } else { if (typed[pos2] != name[pos1 - 1]) { return false; } if (++pos2 >= n2) { return false; } } } while (pos2 < n2) { if (typed[pos2] != typed[pos2 - 1]) { return false; } pos2++; } return true; } };

我的成绩

执行结果:通过 执行用时:0 ms, 在所有 C++ 提交中击败了100.00%的用户 内存消耗:6.3 MB, 在所有 C++ 提交中击败了36.61%的用户

一些想法

本道题需要注意重复的只能是之前的字符。

执行用时为 0 ms 的范例

class Solution { public: bool isLongPressedName(string name, string typed) { if (name == typed) return true; if (name.empty() || typed.empty()) return false; int n = name.size(), m = typed.size(); int i = 0, j = 0; while (i < n && j < m) { if (name[i] == typed[j]) { ++i; ++j; } else if (j > 0 && typed[j] == typed[j - 1]) { while(j < m && typed[j] == typed[j - 1]) ++j; } else { return false; } } while(j < m && typed[j] == typed[j - 1]) ++j; if (i == n && j == m) return true; return false; } };

思考

参见官方解答

最新回复(0)