Given an input string, reverse the string word by word.
For example,
Given s = "
return "
Have you met this question in a real interview? Given s = "
the sky is blue
",return "
blue is sky the
".
Yes
Example
Clarification
public class Solution {- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. - How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
/**
* @param s : A string
* @return : A string
*/
public String reverseWords(String s) {
// write your code
char[] arr = s.trim().toCharArray();
reverse(arr, 0, arr.length-1);
for(int i = 0, j = 0; j <= arr.length; j++){
if(j == arr.length || arr[j] == ' '){
reverse(arr, i, j-1);
i = j+1;
}
}
return new String(arr);
}
private void reverse(char[] s, int left, int right){
while(left < right){
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
}
No comments:
Post a Comment