-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongPressedName.java
More file actions
81 lines (71 loc) · 2.33 KB
/
LongPressedName.java
File metadata and controls
81 lines (71 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package leetcode;
import java.util.LinkedList;
import java.util.List;
/**
* LongPressedName
* https://leetcode-cn.com/problems/long-pressed-name/
*
* @since 2020-10-21
*/
public class LongPressedName {
public static void main(String[] args) {
LongPressedName sol = new LongPressedName();
System.out.println(sol.isLongPressedName("alex", "aaleex"));
System.out.println(sol.isLongPressedName("saeed", "ssaaedd"));
System.out.println(sol.isLongPressedName("leelee", "lleeelee"));
System.out.println(sol.isLongPressedName("laiden", "laiden"));
System.out.println(sol.isLongPressedName("pyplrz", "ppyypllr"));
}
public boolean isLongPressedName(String name, String typed) {
List<Character> nameChar = new LinkedList<>();
List<Integer> nameCharCount = new LinkedList<>();
// count name char
char lastChar = 0;
int lastCharCount = 0;
for (int i = 0; i < name.length(); i++) {
if (name.charAt(i) == lastChar) {
lastCharCount++;
} else {
nameChar.add(lastChar);
nameCharCount.add(lastCharCount);
lastChar = name.charAt(i);
lastCharCount = 1;
}
}
nameChar.add(lastChar);
nameCharCount.add(lastCharCount);
// compare typed char
lastChar = 0;
lastCharCount = 0;
int idx = 0;
for (int i = 0; i < typed.length(); i++) {
if (typed.charAt(i) == lastChar) {
lastCharCount++;
} else {
if (idx >= nameChar.size()) {
return false;
}
if (!nameChar.get(idx).equals(lastChar)) {
return false;
}
if (nameCharCount.get(idx) > lastCharCount) {
return false;
}
lastChar = typed.charAt(i);
lastCharCount = 1;
idx++;
}
}
// bug1: detect shorter typed
if (idx != nameChar.size() - 1) {
return false;
}
if (!nameChar.get(idx).equals(lastChar)) {
return false;
}
if (nameCharCount.get(idx) > lastCharCount) {
return false;
}
return true;
}
}