Leetcode 151 Reverse Words in a String

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Neo233/article/details/85526664

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

Example:  

Input: "the sky is blue",
Output: "blue is sky the".

Note:

  • A word is defined as a sequence of non-space characters.
  • Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
  • You need to reduce multiple spaces between two words to a single space in the reversed string.

Follow up: For C programmers, try to solve it in-place in O(1) space.

这个题的意思是将一串字符倒置。

(1)我的方法是直接将字符串分离出来再进行重新的拼接

public class Solution {
    public String reverseWords(String s) {
        String[] ss = s.trim().split("\\s+");//trim().split("\\s+")
        String a = "";
        for(int i = ss.length - 1;i >= 1 ;--i){
            a += ss[i] + " ";
        }
        return a + ss[0];
    }
}

(2)最佳的是在O(1)的空间复杂度下完成的

public class Solution {
    public String reverseWords(String s) {
        StringBuilder sb = new StringBuilder();
        int index = s.length() - 1;
        while (index >= 0) {
            if (s.charAt(index) == ' ') {
                index--;
                continue;
            }
            int start = s.lastIndexOf(' ', index) + 1;
            sb.append(' ');
            sb.append(s.substring(start, index + 1));//将空格两边的字符进行重新的拼接
            index = start - 1;
        }
        if (sb.length() > 0) sb.deleteCharAt(0);//这一行的意思是将最前面的空格去掉
        return sb.toString();//转化为String
    }
}

猜你喜欢

转载自blog.csdn.net/Neo233/article/details/85526664