# LeetCode.917-只反转字母(Reverse Only Letters)

### 01 看题和准备

• S.length <= 100

• 33 <= S[i].ASCIIcode <= 122

• S不包含\“

### 02 第一种解法

public String reverseOnlyLetters(String S) {
int i = 0, j = S.length()-1;
char[] arr = S.toCharArray();
while (i < j) {
char c = arr[i];
char c2 = arr[j];
if (Character.isLetter(c) && Character.isLetter(c2)) {
arr[i] = c2;
arr[j] = c;
i++;
j--;
} else if (!Character.isLetter(c) && Character.isLetter(c2)) {
i++;
} else if (Character.isLetter(c) && !Character.isLetter(c2)) {
j--;
} else if (!Character.isLetter(c) && !Character.isLetter(c2)) {
i++;
j--;
}
}
return new String(arr);
}

### 03 第二种解法

public String reverseOnlyLetters2(String S) {
int j = S.length()-1, n = S.length();
StringBuilder sb = new StringBuilder();
for (int i=0; i<n; i++) {
if (Character.isLetter(S.charAt(i))) {
while (j>=0 && !Character.isLetter(S.charAt(j))) {
j--;
}
sb.append(S.charAt(j--));
} else {
sb.append(S.charAt(i));
}
}
return sb.toString();
}

### 04 第三种解法

public String reverseOnlyLetters3(String S) {
Stack<Character> stack = new Stack<Character>();
char[] arr = S.toCharArray();
for (char c : arr) {
if (Character.isLetter(c)) {
stack.push(c);
}
}
StringBuilder sb = new StringBuilder();
for (char c : arr) {
if (Character.isLetter(c)) {
sb.append(stack.pop());
} else {
sb.append(c);
}
}
return sb.toString();
}

### 05 小结

posted @ 2019-06-14 08:32 程序员小川 阅读(...) 评论(...) 编辑 收藏