557. Reverse Words in a String I

2018-01-13  本文已影响0人  matrxyz

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();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读