Given a string S
, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.
Example 1:
Input: "ab-cd" Output: "dc-ba"
Example 2:
Input: "a-bC-dEf-ghIj" Output: "j-Ih-gfE-dCba"
Example 3:
Input: "Test1ng-Leet=code-Q!" Output: "Qedo1ct-eeLg=ntse-T!"
Note:
S.length <= 100
33 <= S[i].ASCIIcode <= 122
S
doesn't contain\
or"
给定一个字符串 S
,返回 “反转后的” 字符串,其中不是字母的字符都保留在原地,而所有字母的位置发生反转。
示例 1:
输入:"ab-cd" 输出:"dc-ba"
示例 2:
输入:"a-bC-dEf-ghIj" 输出:"j-Ih-gfE-dCba"
示例 3:
输入:"Test1ng-Leet=code-Q!" 输出:"Qedo1ct-eeLg=ntse-T!"
提示:
S.length <= 100
33 <= S[i].ASCIIcode <= 122
S
中不包含\
or"
解析:
两个指针,一个从头出发,一个从未出发,判断如果是字母,就交换。特别注意如果全部为非字母的情况。
package com.wx.string;
public class Solution917 {
public String reverseOnlyLetters(String S) {
int len = S.length();
char[] chars = S.toCharArray();
int i = 0;
int j = len - 1;
while (i < j) {
while (i < j && !isChar(chars[i])) {
i++;
}
while (i < j && !isChar(chars[j])) {
j--;
}
if (i == len || j < 0) {
return S;
}
swap(chars, i, j);
i++;
j--;
}
return String.valueOf(chars);
}
private boolean isChar(char c) {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
return true;
}
return false;
}
private void swap(char[] chars, int i, int j) {
char c = chars[i];
chars[i] = chars[j];
chars[j] = c;
}
public static void main(String[] args) {
Solution917 solution917 = new Solution917();
String s = "?6C40E";
String s1 = solution917.reverseOnlyLetters(s);
System.out.println(s1);
}
}