Leetcode学习笔记:#917. Reverse Only Letters
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.
实现:
public String reverseOnlyLetters(String S){
StringBuilder sb = new StringBuilder(S);
for(int i = 0. j = S.length(); i < j; i++, j--){
while(i < j && !Character.isLetter(sb.charAt(i))) i++;
while(i < j && !Character.isLetter(sb.charAt(j))) j--;
sb.setChar(i, S.chatAt(j));
sb.setChar(j, S.charAt(i));
}
return sb.toString();
}
思路:
两个指针,一个从前一个从后,每遇到字母就交换,符号等就跳过。