This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
/** | |
* @param str: a string | |
* @return: return a string | |
*/ | |
public char[] reverseWords(char[] str) { | |
// handle corner cases | |
if (str == null || str.length < 2) { | |
return str; | |
} | |
// step #1 flip the whole thing | |
reverse(str, 0, str.length - 1); | |
// System.out.println(Arrays.toString(str)); | |
// step #2 flip each word | |
int left = 0; | |
for (int right = 0; right < str.length - 1; right++) { | |
if (str[right] != ' ') { | |
continue; | |
} | |
reverse(str, left, right - 1); | |
left = right + 1; | |
} | |
// one last reverse | |
reverse(str, left, str.length - 1); | |
return str; | |
} | |
private void reverse(char[] str, int left, int right) { | |
while (left < right) { | |
char tmp = str[left]; | |
str[left] = str[right]; | |
str[right] = tmp; | |
left++; | |
right--; | |
} | |
} | |
} |
No comments:
Post a Comment