Repository navigation
Expand file tree
/
Copy pathBackspaceStringCompareTest.java
More file actions
135 lines (110 loc) · 2.74 KB
/
Copy pathBackspaceStringCompareTest.java
File metadata and controls
135 lines (110 loc) · 2.74 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package org.overmind;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* <a href="https://leetcode.com/problems/backspace-string-compare/">844. Backspace String Compare</a> (Easy)
* <p>
* Compare two strings after applying the backspace character {@code '#'}.
*/
public class BackspaceStringCompareTest {
private final Solution solution = new Solution();
@Test
void example1() {
// when
var result = solution.backspaceCompare("ab#c", "ad#c");
// then
assertThat(result)
.isTrue();
}
@Test
void example2() {
// when
var result = solution.backspaceCompare("ab##", "c#d#");
// then
assertThat(result)
.isTrue();
}
@Test
void example3() {
// when
var result = solution.backspaceCompare("a#c", "b");
// then
assertThat(result)
.isFalse();
}
class Solution {
public boolean backspaceCompare(String first, String second) {
char[] firstChars = first.toCharArray();
char[] secondChars = second.toCharArray();
int firstSkip = 0;
int secondSkip = 0;
int firstIndex = firstChars.length - 1;
int secondIndex = secondChars.length - 1;
while (firstIndex >= 0 && secondIndex >= 0) {
while (firstIndex >= 0) {
if (firstChars[firstIndex] == '#') {
firstSkip++;
firstIndex--;
continue;
}
if (firstSkip > 0) {
firstIndex--;
firstSkip--;
} else {
break;
}
}
while (secondIndex >= 0) {
if (secondChars[secondIndex] == '#') {
secondSkip++;
secondIndex--;
continue;
}
if (secondSkip > 0) {
secondIndex--;
secondSkip--;
} else {
break;
}
}
if (firstIndex >= 0 && secondIndex >= 0) {
if (firstChars[firstIndex] == secondChars[secondIndex]) {
firstIndex--;
secondIndex--;
} else {
return false;
}
} else {
break;
}
}
while (firstIndex >= 0) {
if (firstChars[firstIndex] == '#') {
firstSkip++;
firstIndex--;
continue;
}
if (firstSkip > 0) {
firstIndex--;
firstSkip--;
continue;
}
return false;
}
while (secondIndex >= 0) {
if (secondChars[secondIndex] == '#') {
secondSkip++;
secondIndex--;
continue;
}
if (secondSkip > 0) {
secondIndex--;
secondSkip--;
continue;
}
return false;
}
return true;
}
}
}