-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathOnlyReverseLetter.java
70 lines (44 loc) · 1.16 KB
/
OnlyReverseLetter.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
package other;
import java.util.Stack;
/**
* @Author: Wenhang Chen
* @Description:给定一个字符串 S,返回 “反转后的” 字符串,其中不是字母的字符都保留在原地,而所有字母的位置发生反转。
* <p>
* 示例 1:
* <p>
* 输入:"ab-cd"
* 输出:"dc-ba"
* 示例 2:
* <p>
* 输入:"a-bC-dEf-ghIj"
* 输出:"j-Ih-gfE-dCba"
* 示例 3:
* <p>
* 输入:"Test1ng-Leet=code-Q!"
* 输出:"Qedo1ct-eeLg=ntse-T!"
*
* <p>
* 提示:
* <p>
* S.length <= 100
* 33 <= S[i].ASCIIcode <= 122
* S 中不包含 \ or "
* @Date: Created in 8:59 6/6/2020
* @Modified by:
*/
public class OnlyReverseLetter {
public String reverseOnlyLetters(String S) {
Stack<Character> letters = new Stack();
for (char c : S.toCharArray())
if (Character.isLetter(c))
letters.push(c);
StringBuilder ans = new StringBuilder();
for (char c : S.toCharArray()) {
if (Character.isLetter(c))
ans.append(letters.pop());
else
ans.append(c);
}
return ans.toString();
}
}