1. 题目描述
题目链接:翻转字符串
2. 题目分析
- 剑指offer的原题。在剑指offer中,采取的方法是:对字符串进行处理,将首尾的空格去掉,再对整个字符串进行翻转,再翻转每一个小字符串,最后处理多余的空格,返回即可
- 这里我采取的是双指针的做法,比较容易理解和书写。
- 我们先判断异常的字符串:
if(s == null || s.length() == 0 || s.trim().length() == 0){ return ""; }
- 我们定义i、j,从字符串的后面开始遍历,当i遇到空格时,我们将i+1~j(这里的i指向空格)存入StringBuffer中,然后再跑i,遇到字母的时候停止,
j = i
- 这个题需要注意的点:注意存入的是i+1~j、防止越界,每次判断i>=0
3. 题目代码
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
s = reverseWords(s);
System.out.print(s);
}
public static String reverseWords(String s) {
if (s == null || s.length() == 0 || s.trim().length() == 0) {
return "";
}
s = s.trim();
StringBuffer buffer = new StringBuffer();
int i = s.length() - 1;
int j = s.length() - 1;
while (i >= 0 && j >= 0) {
while (i >= 0 && s.charAt(i) != ' ') {
i--;
}
buffer.append(s.substring(i + 1, j + 1) + " ");
while (i >= 0 && s.charAt(i) == ' ') {
i--;
}
j = i;
}
return buffer.toString();
}
}