【LeetCode】557. Reverse Words in a String III
Difficulty: Easy
More:【目录】LeetCode Java实现
Description
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.
Intuition
Find the start and end of each word, then reverse each word.
Solution
public String reverseWords(String s) { if(s==null || s.length()==0) return s; StringBuilder sb = new StringBuilder(s); int start=0; int end=0; while(start<s.length()){ while(end<s.length() && s.charAt(end)!=' ') end++; reverse(sb,start,end-1); end++; start=end; } return sb.toString(); } private void reverse(StringBuilder sb,int start,int end){ while(start<end){ char temp=sb.charAt(start); sb.setCharAt(start,sb.charAt(end)); sb.setCharAt(end,temp); start++; end--; } }
Complexity
Time complexity : O(n)
Space complexity : O(1)
What I've learned
1. Learn how to get the start and end of each word.
More:【目录】LeetCode Java实现