[LeetCode] 557. Reverse Words in a String III

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.

 

题意,翻转每个字符串中的单词

道理还是翻转字符串就是换了个形式罢了,按空格拆就好

class Solution {
    private String reverseString(String s) {
        String str = "";
        for (int i = s.length() - 1; i >= 0; i --)
            str += s.charAt(i);
        return str;
    }
    public String reverseWords(String s) {
        String str = "";
        String temp = "";
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' ') {
                str += reverseString(temp);
                str += " ";
                temp = "";
            }
            else temp += s.charAt(i);
        }
        str += reverseString(temp);
        return str;
    }
}

 

posted @ 2018-10-09 22:35  C`Moriarty  阅读(86)  评论(0编辑  收藏  举报
/* 鼠标点击求赞文字特效 */ /*鼠标跟随效果*/