Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a15f0c9

Browse files
Create Resulting String After Adjacent Removals.java
1 parent 78832b3 commit a15f0c9

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public String resultingString(String s) {
3+
Stack<Character> stack = new Stack<>();
4+
for (char c : s.toCharArray()) {
5+
if (!stack.isEmpty() && isAdjacent(stack.peek(), c)) {
6+
stack.pop();
7+
} else {
8+
stack.push(c);
9+
}
10+
}
11+
StringBuilder result = new StringBuilder();
12+
for (char c : stack) {
13+
result.append(c);
14+
}
15+
return result.toString();
16+
}
17+
18+
private static boolean isAdjacent(char first, char second) {
19+
return Math.abs(first - second) == 1 || (first == 'a' && second == 'z') || (first == 'z' && second == 'a');
20+
}
21+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /