leetcode題解-151. Reverse Words in a String && 557. Reverse Words in a String III

這兩道題目都是反轉字符串中單詞類型的,II收費所以沒刷,先看着兩道。

151, 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) space.

本題是將字符串中的所有單詞反向排列,很簡單,直接split即可,但是要注意單詞之間可能會有多個空格,而且字符串的開頭和結尾也都可能會出現空格,所以要先trim在split,而且切分的時候要對多個空格進行匹配切分,不能只對單個空格切分。代碼如下所示:

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

此外,我們也可以不適用內置的切分函數,自己按照字符串進行切分並重新拼接,代碼效率會略有提升,如下所示:

    public static String reverseWords1(String s) {
        if (s == null)
            return null;

        char[] str = s.toCharArray();
        int start = 0, end = str.length - 1;

        // Trim start of string
        while (start <= end && str[start] == ' ')
            start++;

        //Trim end of string
        while (end >= 0 && str[end] == ' ')
            end--;

        if (start > end)
            return new String("");

        int i = start;
        while (i <= end) {
            if (str[i] != ' ') {
                // case when i points to a start of word -  find the word reverse it
                int j = i + 1;
                while (j <= end && str[j] != ' ')
                    j++;
                reverse(str, i, j - 1);
                i = j;
            } else {
                if (str[i - 1] == ' ') {
                    //case when prev char is also space - shift char to left by 1 and decrease end pointer
                    int j = i;
                    while (j <= end - 1) {
                        str[j] = str[j + 1];
                        j++;
                    }
                    end--;
                } else
                    // case when there is just single space
                    i++;
            }
        }
        //Now that all words are reversed, time to reverse the entire string pointed by start and end - This step reverses the words in string
        reverse(str, start, end);
        // return new string object pointed by start with len = end -start + 1
        return new String(str, start, end - start + 1);
    }

    private static void reverse(char[] str, int begin, int end) {
        while (begin < end) {
            char temp = str[begin];
            str[begin] = str[end];
            str[end] = temp;
            begin++;
            end--;
        }
    }

557,Reverse Words in a String III,題目:

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.

本提就跟家簡單了,每個單詞都以空格分開,需要做的就是將每個單詞進行反向翻轉,代碼如下,可以擊敗35%的用戶:

    public static String reverseWords(String s) {
        if(s.equals("") || s.equals(" "))
            return s;
        char[] ss = s.toCharArray();
        int i = 0, j;
        StringBuilder res = new StringBuilder();
        while(i<ss.length){
            j=i;
            while(j < ss.length && ss[j] != ' ') j++;
            res.append(reverse(ss, i, j-1));
            res.append(" ");
            i=j+1;
        }
        res.deleteCharAt(ss.length);
        return res.toString();
    }

    public static String reverse(char[] ss, int i, int j){
        String res = "";
        for(int k=j; k>=i; k--)
            res += ss[k];
        return res;
    }

還有一種更爲簡潔的方法,使用內置的reverse函數進行翻轉,效率略有提升,可以擊敗60%的用戶:

    public String reverseWords1(String s) {
        String[] str = s.split(" ");
        for (int i = 0; i < str.length; i++) str[i] = new StringBuilder(str[i]).reverse().toString();
        StringBuilder result = new StringBuilder();
        for (String st : str) result.append(st + " ");
        return result.toString().trim();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章