[Leetcode] Reverse Words in a String 反轉單詞順序

Reverse Words in a String

Given an input string, reverse the string word by word.正則表達式

For example, Given s = "the sky is blue", return "blue is sky the".數組

Update (2015-02-12): For C programmers: Try to solve it in-place in O(1) spaceapp

使用API

複雜度

時間 O(N) 空間 O(N)ui

思路

將單詞根據空格split開來存入一個字符串數組,而後將該數組反轉便可。spa

注意

  • 先用trim()將先後無用的空格去掉指針

  • 用正則表達式" +"來匹配一個或多個空格code

代碼

public class Solution {
    public String reverseWords(String s) {
        String[] words = s.trim().split(" +");
        int len = words.length;
        StringBuilder result = new StringBuilder();
        for(int i = len -1; i>=0;i--){
            result.append(words[i]);
            if(i!=0) result.append(" ");
        }
        return result.toString();
    }
}

雙指針交換法

複雜度

時間 O(N) 空間 O(N) 若是輸入時char數組則是O(1)字符串

思路

先將字符串轉換成char的數組,而後將整個數組反轉。而後咱們再對每個單詞單獨的反轉一次,方法是用兩個指針記錄當前單詞的起始位置和終止位置,遇到空格就進入下一個單詞。input

代碼

public class Solution {
    public String reverseWords(String s) {
        s = s.trim();
        char[] str = s.toCharArray();
        // 先反轉整個數組
        reverse(str, 0, str.length - 1);
        int start = 0, end = 0;
        for(int i = 0; i < s.length(); i++){
            if(str[i]!=' '){
                end++;
            } else {
                // 反轉每一個單詞
                reverse(str, start, end - 1);
                end++;
                start = end;
            }
        }
        return String.valueOf(str);
    }
    
    public void reverse(char[] str, int start, int end){
        while(start < end){
            char tmp = str[start];
            str[start] = str[end];
            str[end] = tmp;
            start++;
            end--;
        }
    }
}

Reverse Words in a String II

Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.string

The input string does not contain leading or trailing spaces and the words are always separated by a single space.

For example, Given s = "the sky is blue", return "blue is sky the".
Could you do it in-place without allocating extra space?

雙指針交換法

複雜度

時間 O(N) 空間 O(1)

思路

這題就是Java版的Inplace作法了,先反轉整個數組,再對每一個詞反轉。

代碼

public class Solution {
    public void reverseWords(char[] s) {
        reverse(s, 0, s.length - 1);
        int start = 0;
        for(int i = 0; i < s.length; i++){
            if(s[i] == ' '){
                reverse(s, start, i - 1);
                start = i + 1;
            }
        }
        reverse(s, start, s.length - 1);
    }
    
    public void reverse(char[] s, int start, int end){
        while(start < end){
            char tmp = s[start];
            s[start] = s[end];
            s[end] = tmp;
            start++;
            end--;
        }
    }
}
相關文章
相關標籤/搜索