-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathBackspaceStringCompare.java
56 lines (53 loc) · 1.52 KB
/
BackspaceStringCompare.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
/*https://leetcode.com/problems/backspace-string-compare/*/
class Solution {
public boolean backspaceCompare(String s, String t) {
int sLength = s.length(), tLength = t.length();
Stack<Character> sStack = new Stack<Character>();
Stack<Character> tStack = new Stack<Character>();
for (char ch : s.toCharArray())
{
if (ch == '#')
{
if (!sStack.isEmpty()) sStack.pop();
}
else sStack.push(ch);
}
for (char ch : t.toCharArray())
{
if (ch == '#')
{
if (!tStack.isEmpty())tStack.pop();
}
else tStack.push(ch);
}
if (sStack.size() != tStack.size()) return false;
while (!sStack.isEmpty())
{
if (sStack.peek() != tStack.peek()) return false;
sStack.pop();
tStack.pop();
}
return true;
}
}
class Solution {
public boolean backspaceCompare(String S, String T) {
String s = getString(S);
String t = getString(T);
return s.equals(t);
}
private String getString(String s) {
StringBuilder str = new StringBuilder();
char[] c = s.toCharArray();
for (char ch : c) {
if (ch == '#') {
if ( str.length() != 0) {
str.deleteCharAt(str.length() - 1);
}
} else {
str.append(ch);
}
}
return str.toString();
}
}