-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode917_ReverseOnlyLetters.java
More file actions
42 lines (34 loc) · 1.18 KB
/
Copy pathleetcode917_ReverseOnlyLetters.java
File metadata and controls
42 lines (34 loc) · 1.18 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
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class leetcode917_ReverseOnlyLetters {
public String reverseOnlyLetters(String S) {
Stack<Character> q = new Stack<>();
char ch;
int asciiVal;
StringBuilder sb = new StringBuilder(S);
//Getting all the letters
for(int i=0;i<S.length();i++) {
ch = S.charAt(i);
asciiVal = (int)ch;
if ( (asciiVal >= 97 && asciiVal <=122) || (asciiVal >= 65 && asciiVal <= 90)) {
q.add(ch);
}
}
//replacing all the letters in the reverse order
for(int i=0;i<S.length();i++) {
ch = S.charAt(i);
asciiVal = (int)ch;
if ( (asciiVal >= 97 && asciiVal <=122) || (asciiVal >= 65 && asciiVal <= 90)) {
sb.setCharAt(i,q.pop());
}
}
return sb.toString();
}
public static void main(String[] args) {
String str = "Test1ng-Leet=code-Q!";
leetcode917_ReverseOnlyLetters obj = new leetcode917_ReverseOnlyLetters();
String res = obj.reverseOnlyLetters(str);
System.out.println(res);
}
}