Skip to content

Commit c897f17

Browse files
committed
LeetCode 925. 长按键入
1 parent 411ef74 commit c897f17

File tree

1 file changed

+119
-0
lines changed

1 file changed

+119
-0
lines changed
+119
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4uanNkZWxpdnIubmV0L2doL2Nob2NvbGF0ZTE5OTkvY2RuL2ltZy8yMDIwMDgyODE0NTUyMS5qcGc?x-oss-process=image/format,png)
2+
>仰望星空的人,不应该被嘲笑
3+
4+
## 题目描述
5+
你的朋友正在使用键盘输入他的名字 `name`。偶尔,在键入字符 `c` 时,按键可能会被长按,而字符可能被输入 1 次或多次。
6+
7+
你将会检查键盘输入的字符 `typed`。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 `True`
8+
9+
10+
11+
示例 1:
12+
13+
```javascript
14+
输入:name = "alex", typed = "aaleex"
15+
输出:true
16+
解释:'alex' 中的 'a''e' 被长按。
17+
```
18+
19+
示例 2:
20+
21+
```javascript
22+
输入:name = "saeed", typed = "ssaaedd"
23+
输出:false
24+
解释:'e' 一定需要被键入两次,但在 typed 的输出中不是这样。
25+
```
26+
27+
示例 3:
28+
29+
```javascript
30+
输入:name = "leelee", typed = "lleeelee"
31+
输出:true
32+
```
33+
34+
示例 4:
35+
36+
```javascript
37+
输入:name = "laiden", typed = "laiden"
38+
输出:true
39+
解释:长按名字中的字符并不是必要的。
40+
```
41+
42+
43+
44+
提示:
45+
46+
- `name.length` <= 1000
47+
- `typed.length` <= 1000
48+
- `name``typed` 的字符都是小写字母。
49+
50+
51+
来源:力扣(LeetCode)
52+
链接:https://leetcode-cn.com/problems/long-pressed-name
53+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
54+
55+
56+
57+
58+
## 解题思路
59+
显而易见,采用双指针做法,通过 `cnt` 计数统计字符匹配成功个数,然后通过双指针进行比较匹配,其中有几个地方注意一下:
60+
61+
- 如果 `typed``name` 的当前索引前一位都不相等的话,那么名字就不对应,直接跳出去,这里算是小小的优化了一下。
62+
-`typed` 走完才能跳出去,如果是 `i == n` 就跳出去的话,这种情况:name:abc | typed:abcd 就会判断出错
63+
64+
65+
```javascript
66+
/**
67+
* @param {string} name
68+
* @param {string} typed
69+
* @return {boolean}
70+
*/
71+
var isLongPressedName = function (name, typed) {
72+
let n = name.length; // 求出字符串长度
73+
let m = typed.length;
74+
let cnt = 0; // 统计匹配成功个数
75+
let i = 0, j = 0; // 双指针
76+
let flag = false; // 判断是否中途遇到不匹配阶段
77+
while (1) {
78+
if (name[i] == typed[j]) { // 匹配成功
79+
i++ , cnt++ , j++;
80+
} else {
81+
if (typed[j] == name[i - 1]) {
82+
j++;
83+
} else {
84+
// 如果 typed 和 name 当前索引前一位都不相等的话,那么名字就不对应,直接跳出去
85+
flag = true;
86+
}
87+
}
88+
if (flag) break;
89+
if (j == m) break; // 当 typed走完才能跳出去,如果是 i == n 就跳出去的话,这种情况:abc | abcd 就会判断出错
90+
}
91+
if (cnt === n && j === m) return true;
92+
else return false;
93+
};
94+
```
95+
96+
97+
98+
99+
## 最后
100+
文章产出不易,还望各位小伙伴们支持一波!
101+
102+
往期精选:
103+
104+
<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a>
105+
106+
<a href="https://github.com/Chocolate1999/leetcode-javascript">leetcode-javascript:LeetCode 力扣的 JavaScript 解题仓库,前端刷题路线(思维导图)</a>
107+
108+
小伙伴们可以在Issues中提交自己的解题代码,🤝 欢迎Contributing,可打卡刷题,Give a ⭐️ if this project helped you!
109+
110+
111+
<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~
112+
113+
![](https://img-blog.csdnimg.cn/2020090211491121.png#pic_center)
114+
115+
```javascript
116+
学如逆水行舟,不进则退
117+
```
118+
119+

0 commit comments

Comments
 (0)