字符串单词翻转总结几种常见方法

时间:2021-06-06 23:59:04

leetcode地址:https://leetcode.com/problems/reverse-words-in-a-string

Given an input string, reverse the string word by word.

eg.
Given s = "the sky is blue",

return "blue is sky the".

1.直接使用split()方法:

private void reverseSentence(String sentence) {
if(sentence==null)
return;
String[] str = sentence.split("\\s+");
//String[] str = sentence.split(" ");
for (int i = 0; i < str.length; i++) {
System.out.print(str[i]+" ");
}
System.out.println();
StringBuffer sb = new StringBuffer();
for (int i = str.length-1; i >=0; i--) {
sb.append(str[i]+" ");
}
System.out.println(sb);
}

该方法无法处理输入样例:“”,因为输出会是“ ”(带有空格)。

2.不实用split()方法:

ArrayList<String> word = new ArrayList<String>();
public String reverseWords(String s) {
int wordNum = calWordNum(s);

StringBuffer sb = new StringBuffer();
for(int i = 0;i<wordNum;i++){
sb.append(word.get(wordNum-i-1));
if(i!=wordNum - 1){
sb.append(" ");
}
}
return sb.toString();
}

private int calWordNum(String s){
int cursor = 0;
int wordNum = 0;
StringBuffer sb = new StringBuffer();
for(int i = 0;i < s.length();i++)
{
if(i==0){//判断起始位置是否为空格
if(s.charAt(i)==' '){
continue;
}else if(s.length()!= 1){
sb.append(s.charAt(i));
cursor++;
}else if(s.length()==1){
sb.append(s.charAt(i));
word.add(sb.toString());
wordNum++;
}
}else if(i==s.length() - 1){//判断结束位置是否为空格
if(s.charAt(i)==' '){
if(cursor != 0){
wordNum++;
word.add(sb.toString());
}
}else{
if(cursor==0){
wordNum++;
sb.append(s.charAt(i));
word.add(sb.toString());
}else{
sb.append(s.charAt(i));
word.add(sb.toString());
wordNum++;
}
}
}else{
if(s.charAt(i)==' '){
if(cursor==0){
continue;
}else if(cursor!=0){
cursor = 0;
wordNum++;
word.add(sb.toString());
sb.delete(0,sb.length());
}
}else{
sb.append(s.charAt(i));
cursor++;
}
}
}
return wordNum;
}

参考: 点击打开链接

3.对split()方法进行改进:

public String reverseWords(String input) {
final StringBuilder stringBuilder = new StringBuilder();
for (final String part : input.split("\\s+")) {
if (!part.isEmpty()) {
if (stringBuilder.length() > 0) {
stringBuilder.insert(0, " ");
}
stringBuilder.insert(0, part);
}
}
return stringBuilder.toString();
}

参考:点击打开链接

注:2,3两种方法在leetcode上均能通过。