一:解题思路
这道题目是反转字符串的变形题目。我们只需要将每个单词作为一个单独的字符串进行反转即可。
二:完整代码示例 (C++版和Java版)
C++:
Time:O(n),Space:O(1),因为C++语言能够直接修改源字符串,所以不需要申请一个额外的数组空间出来。
class Solution { public: string reverseWords(string s) { if (s.length() == 0) return s; int start = 0; int end = 0; while (start < s.length()) { while (end < s.length() && s[end] != ' ') end++; for (int i = start, j = end - 1; i < j; i++, j--) { char temp = s[i]; s[i] = s[j]; s[j] = temp; } start = end + 1; end = start; } return s; } };
Java:
Time:O(n),Space:O(n),因为Java语言不能够直接修改源字符串,所以需要申请一个额外的数组空间出来。
class Solution { public String reverseWords(String s) { if(s==null||s.length()==0) return s; char[] c=s.toCharArray(); int start=0; int end=0; int n=c.length; while(start<n) { while(end<n && c[end]!=' ') end++; for(int i=start,j=end-1;i<j;i++,j--) { char temp=c[i]; c[i]=c[j]; c[j]=temp; } start=end+1; end=start; } return new String(c); } }