-
Notifications
You must be signed in to change notification settings - Fork 0
/
LongPressedName.java
83 lines (68 loc) · 2.09 KB
/
LongPressedName.java
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
82
83
// LeetCode_925
// 2021.04.28
// Easy
import java.util.Stack;
public class LongPressedName {
public static void main(String[] args) {
System.out.println(new LongPressedName().isLongPressedName("saeed", "ssaaedd"));
}
public boolean isLongPressedName(String name, String typed) {
StringBuilder str = new StringBuilder(name);
StringBuilder typ = new StringBuilder(typed);
int strIdx = 0, typIdx = 0;
boolean flag = true;
Stack<Character> stk = new Stack<>();
while(typIdx != typed.length()){
if(stk.empty()) {
stk.push(str.charAt(strIdx));
strIdx++;
}
if(typ.charAt(typIdx) == stk.peek()){
typIdx++;
}else {
try {
stk.push(str.charAt(strIdx));
strIdx++;
if(typ.charAt(typIdx) == stk.peek()){
typIdx++;
}else {
flag = false;
break;
}
}catch (IndexOutOfBoundsException e){
break;
}
}
}
return flag;
}
}
/* USE_TWOPointer 출처: leetcode
class Solution {
public boolean isLongPressedName(String name, String typed) {
int np = 0, tp = 0;
char[] name_chars = name.toCharArray();
char[] typed_chars = typed.toCharArray();
while (np < name_chars.length && tp < typed_chars.length) {
if (name_chars[np] == typed_chars[tp]) {
np += 1;
tp += 1;
} else if (tp >= 1 && typed_chars[tp] == typed_chars[tp - 1]) {
tp += 1;
} else {
return false;
}
}
if (np != name_chars.length) {
return false;
} else {
while (tp < typed_chars.length) {
if (typed_chars[tp] != typed_chars[tp - 1])
return false;
tp += 1;
}
}
return true;
}
}
*/