For example,
Given s = "the sky is blue",
return "blue is sky the".
Idea: The problem itself is not hard. However, if we want to solve the problem in place (O(1) space), there are two special cases to be handled before going to the problem itself.
1) we need to remove the spaces in the front and at the end of the input string.
2) we need to replace the spaces between words with single spaces.
The algorithm is simple. First reverse the whole string. Then reverse each section whenever we meet a space or reach the end. For example:
"the sky is blue"
reverse the whole string ->"eulb si kys eht"
meet first space ->"blue si kys eht"
meet second space ->"blue is kys eht"
meet third space ->"blue is sky eht"
reach the end ->"blue is sky the"
Time: O(n) Space: O(1)
Code:
public class Solution {
public String reverseWords(String s) {
s=s.trim();
s=s.replaceAll("\\s+"," ");
if(s.length()<=1)
return s;
StringBuilder builder=new StringBuilder(s);
reverse(builder,0,builder.length()-1);
int leftBound=0;
while(leftBound<builder.length()&&builder.charAt(leftBound)==' ')
leftBound++;
for(int i=leftBound;i<=builder.length();i++)
{
if(i==builder.length()||builder.charAt(i)==' ')
{
reverse(builder,leftBound,i-1);
leftBound=i+1;
}
}
return builder.toString();
}
public void reverse(StringBuilder builder, int left, int right)
{
while(left<right)
{
char tmp=builder.charAt(left);
builder.setCharAt(left,builder.charAt(right));
builder.setCharAt(right,tmp);
left++;
right--;
}
}
}
Code without trim() and replace: public class ReverseWords {
public ReverseWords()
{
String input=" this is a fox ";
System.out.println("'"+reverse(input)+"'");
}
public static String reverse(String s)
{
char[] chars=s.toCharArray();
reverseCharArray(chars,0,chars.length-1);
int left=0;
int start=0;
while(left<chars.length)
{
if(chars[left]==' ')
left++;
else
{
int right=left;
while(right<chars.length&&chars[right]!=' ')
right++;
reverseCharArray(chars,left,right-1);
copyWord(chars,start,left,right-1);
start+=(right-left);
chars[start]=' ';
start++;
left=right;
}
}
String tmp=new String(chars);
return tmp.substring(0,start-1);
}
public static void reverseCharArray(char[] chars,int start,int end)
{
for(int i=start,j=end;i<=j;i++,j--)
{
char tmp=chars[i];
chars[i]=chars[j];
chars[j]=tmp;
}
}
public static void copyWord(char[] chars,int start,int fromStart,int fromEnd)
{
for(int i=fromStart;i<=fromEnd;i++)
{
chars[start]=chars[i];
start++;
}
}
}
No comments:
Post a Comment