天天看點

LeetCode 557:反轉字元串中的單詞 III Reverse Words in a String III

公衆号:愛寫bug(ID:icodebugs)

給定一個字元串,你需要反轉字元串中每個單詞的字元順序,同時仍保留白格和單詞的初始順序。

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.

示例 1:

輸入: "Let's take LeetCode contest"
輸出: "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.

解題思路:

​ 每次遇到空格字元,就把 從上一次空格字元開始到該空格字元止之間的所有字元反轉一下即可,隻需要注意最後一個字元結束時,并不是空格字元,要再加一個判斷是否是已經索引到最後一位。

'abc def'                    原字元串

['a' , 'b' , 'c' , '  ' , 'd' , 'e' ,'f']    轉成char[]型數組

['c' , 'b' , 'a' , '  '...]                 周遊數組,遇到第一個空格,把該空格到上個空格之間的字母反轉

[... '  ' ,  'd' , 'e' ,'f']               周遊到最後一位,不是空格,依然要反轉到前一個空格間的字母

[... '  ' ,  'f' , 'd' ,'e']            反轉

'cba fde'                    轉成字元串輸出           

Java:

class Solution {
    public String reverseWords(String s) {
        int sLen = s.length(), k = 0, j = 0;//j記錄空格字元前的索引位置
        char strs[] = s.toCharArray(), temp;//轉為字元數組
        for (int i = 0; i < sLen; i++) {
            if (strs[i] == ' ') j = i - 1;//遇到空格字元j值減1,為截取的字母段的最後一個字母的索引
            else if (i == sLen - 1) j = i;//如果到最後一位,則j值不應該再減1
            else continue;
            for (; j >= k; j--, k++) {//交換位置
                temp = strs[j];
                strs[j] = strs[k];
                strs[k] = temp;
            }
            k = i + 1;//k記錄空格字元後的索引位置
        }
        return String.valueOf(strs);
    }
}           

python不再複現上述定義指針解題的思路,這裡再次投機取巧,利用 python 切片特性及

split()

join()

函數解題,解題思路:

'abc def gh'                原字元串

'hg fed cba'                切片特性反轉字元串

['hg'  , 'fed' , 'cba']           split()分割字元串

['cba' , 'fed' , 'hg']           切片反轉數組

'cba fed hg'                拼接成字元串           

Python3:

class Solution:
    def reverseWords(self, s: str) -> str:
        return ' '.join(s[::-1].split()[::-1])