描述
給定輸入的字符數(shù)組玖详,逐詞翻轉(zhuǎn)數(shù)組。單詞被定義為不包含空格的字符串.
輸入字符數(shù)組不包含前導(dǎo)或尾部空格勤讽,單詞總是用單個(gè)空格分隔蟋座。
樣例
給定 s = "the sky is blue",
翻轉(zhuǎn)之后 : "blue is sky the"
挑戰(zhàn)
你能在不分配額外空間的情況下原地解決這個(gè)問題嗎?
實(shí)現(xiàn):
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;
}
}