- 557. Reverse Words in a String I
- 557. Reverse Words in a String I
- 557. Reverse Words in a String I
- 557. Reverse Words in a String I
- 557. Reverse Words in a String I
- 557. Reverse Words in a String I
- 557. Reverse Words in a String I
- 557. Reverse Words in a String I
- [Leetcode]151. Reverse Words in
- 186. Reverse Words in a String I
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:遍历
思路:
Time Complexity: O(N) Space Complexity: O(N)
Solution Code:
class Solution {
public String reverseWords(String s) {
String[] str = s.split(" ");
for (int i = 0; i < str.length; i++) {
str[i] = new StringBuilder(str[i]).reverse().toString();
}
StringBuilder result = new StringBuilder();
for (String st : str) {
result.append(st + " ");
}
return result.toString().trim();
}
}
网友评论