給定一個字符串,逐個翻轉字符串中的每個單詞。
示例:
輸入: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
輸出: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
注意:
單詞的定義是不包含空格的一系列字符
輸入字符串中不會包含前置或尾隨的空格
單詞與單詞之間永遠是以單個空格隔開的
進階:使用?O(1) 額外空間復雜度的原地解法。
思路:先反轉每個單詞,然后總體再翻轉。
class Solution {public void reverseWords(char[] s) {int start=0;for(int i=0;i<s.length;i++){if(s[i]==' '){reverseWord(s,start,i-1);start=i+1;}}reverseWord(s,start,s.length-1);reverseWord(s,0,s.length-1);}public void reverseWord(char[] s,int start,int end){char temp;while(start<end){temp=s[start];s[start]=s[end];s[end]=temp;start++;end--;}}
}