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>想法如下
- 利用空白來切割字串
- 反轉切割出來的子字串,再串起來
C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
沒有留言:
張貼留言