2017年12月13日 星期三

[LeetCode] 557. Reverse Words in a String III

轉自LeetCode

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"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
<Solution>

想法如下
  • 利用空白來切割字串
  • 反轉切割出來的子字串,再串起來
code 如下

C++
class Solution {
public:
string reverseWords(string s) {
istringstream iss(s);
ostringstream oss;
string word;
while(iss >> word) {
reverse(word.begin(), word.end());
oss << word << " ";
}
string ans = oss.str();
ans.pop_back();
return ans;
}
};

Java
class Solution {
public String reverseWords(String s) {
String[] words = s.split(" ");
for(int i = 0; i < words.length; ++i) {
words[i] = new StringBuilder(words[i]).reverse().toString();
}
StringBuilder sb = new StringBuilder();
for(final String str: words) {
sb.append(str);
sb.append(" ");
}
return sb.toString().trim();
}
}

沒有留言:

張貼留言