LeetCode 917 Reverse Only Letters

题意

反转字符串,但只反转字符串中的字母,即 a-zA-Z。其他的字符保持原位。

Example 1:

1
2
Input: "ab-cd"
Output: "dc-ba"

Example 2:

1
2
Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"

Example 3:

1
2
Input: "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"

解法

将字符串转为字符数组,用两个指针,从两端向中间走, 依次找下一个字母进行交换,直到两个指针相碰撞。

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
class Solution {
public String reverseOnlyLetters(String S) {
char[] chars = S.toCharArray();
int i = 0, j = chars.length - 1;
while (i < j) {
while (i < j && !isLetter(chars[i])) {
i++;
}
while (i < j && !isLetter(chars[j])) {
j--;
}
if (i < j) {
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
i++;
j--;
}
}
return new String(chars);
}

private boolean isLetter(char c) {
return (c >= 65 && c <= 90) || (c >= 97 && c <= 122);
}
}

Runtime: 5 ms, faster than 93.93% of Java online submissions for Reverse Only Letters.

  • 本文作者: 赵俊
  • 本文链接: http://www.zhaojun.im/leetcode-917/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!