题解 | #单词倒排#
单词倒排
http://www.nowcoder.com/practice/81544a4989df4109b33c2d65037c5836
双指针 leetcode也有类似:https://leetcode-cn.com/problems/reverse-words-in-a-string/
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++) {
if (!Character.isLetter(c[i])) {
c[i] = ' ';
}
}
// 双指针法
int left = 0;
int right = c.length - 1;
StringBuilder str = new StringBuilder();
// 下面两行主要为了去除字符串前后的空格
while (c[left] == ' ') left++;
while (c[right] == ' ') right--;
while (left <= right) {
int index = right;
while (index >= left && c[index] != ' ' ) index--;
for (int i = index + 1 ; i <= right ; i++ ) str.append( c[i] );
// 这一句可以使字符串最后没有空格,方便直接返回
if (index > left) str.append(' ');
while ( index >= left && c[index] == ' ' ) index--;
right = index;
}
System.out.println(str.toString());
}
}