您的位置:首页 > 其它

leetcode557. Reverse Words in a String III

2017-06-05 21:35 429 查看

557. Reverse Words in a String III

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"


解法

先转为字符串数组,没遇到一个空格,将前一个空格和现在的空格之间的字符串反转一次。因为最后一个单词结尾不会有空格,所以单独再反转一次。

public class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0) {
return "";
}

char[] charArray = s.toCharArray();
int i = 0;
for (int j = 0; j < charArray.length; j++) {
if (charArray[j] == ' ') {
reverse(charArray, i, j - 1);
i = j + 1;
}
}
reverse(charArray, i, charArray.length - 1);
return new String(charArray);
}
public void reverse(char[] s, int left, int right) {
while (left < right) {
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: