描述
给定输入的字符数组,逐词翻转数组。单词被定义为不包含空格的字符串.
输入字符数组不包含前导或尾部空格,单词总是用单个空格分隔。
样例
给定 s = "the sky is blue",
翻转之后 : "blue is sky the"
挑战
你能在不分配额外空间的情况下原地解决这个问题吗?
实现:
public class Solution {
/**
* @param str: a string
* @return: return a string
*/
public char[] reverseWords(char[] str) {
// write your code here
int j = str.length - 1;
char[] newChar = reverse(str, 0, j);
for (int i = 0; i < j; i++) {
int start = i;
while (i <= j && newChar[i] != 32) {
i++;
}
if (i - start > 0) {
newChar = reverse(newChar, start, i - 1);
}
if (i - 1 != j) {
newChar[i] = 32;
}
}
return newChar;
}
public char[] reverse(char[] str, int left, int right) {
int length = right - left;
char temp;
while (left <= right) {
temp = str[left];
str[left] = str[right];
str[right] = temp;
left++;
right--;
}
return str;
}
}