给定一个字符串,逐个翻转字符串中的每个单词。
示例:
输入: ["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--;}}
}