題目:反轉字串中的單詞 III
給定一個字串,你需要反轉字串中每個單詞的字元順序,同時仍保留空格和單詞的初始順序。
複製程式碼
示例:
輸入: "Let's take LeetCode contest"
輸出: "s'teL ekat edoCteeL tsetnoc"
複製程式碼
思考:
首先根據空格將字串分割,然後將每一個子串翻轉,再把所有子串拼接,中間加上空格,最後一個空格需要去掉。
複製程式碼
實現:
class Solution {
public String reverseWords(String s) {
String[] split = s.split(" ");
String[] result = new String[split.length];
for (int count = 0; count<split.length; count++) {
result[count] = reverseString(split[count].toCharArray());
}
String resultStr = "";
for (int count = 0; count < result.length; count++) {
resultStr += result[count] + " ";
}
return resultStr.substring(0, resultStr.length() - 1);
}
public String reverseString(char[] s) {
for (int i = 0; i < s.length / 2; i++) {
s[i] = (char) (s[i] ^ s[s.length - 1 - i]);
s[s.length - 1 - i] = (char) (s[i] ^ s[s.length - 1 - i]);
s[i] = (char) (s[i] ^ s[s.length - 1 - i]);
}
return new String(s);
}
}
複製程式碼