美文网首页
557. Reverse Words in a String I

557. Reverse Words in a String I

作者: matrxyz | 来源:发表于2018-01-13 11:00 被阅读0次

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();
    }
}

相关文章

网友评论

      本文标题:557. Reverse Words in a String I

      本文链接:https://www.haomeiwen.com/subject/spccoxtx.html