More:【目錄】LeetCode Java實現html
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.java
Example 1:post
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.ui
Find the start and end of each word, then reverse each word.spa
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--; } }
Time complexity : O(n)htm
Space complexity : O(1)blog
1. Learn how to get the start and end of each word.ip
More:【目錄】LeetCode Java實現get