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.

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
思路:
1.遇到空格就翻转,最后一个字符串必翻转。
2.判空是必须的。
3.最好写一个翻转函数,用来单独调用。
public class Solution {
    public String reverseWords(String s) {
        if(s==null||s.length()==0)//判空
            return   "";
        String temp="";
        int q=0;//q指向每一个字符串的开头
        for(int p=0;p<s.length();p++)//指向字符串的结尾处的空格
        {
            if(s.charAt(p)==' ')//只要遇到空格,就条用翻转。
            {
                temp+=reverseword(s.substring(q, p));
                temp+=s.charAt(p);
                q=p+1;
            }
        }
        temp+=reverseword(s.substring(q,s.length()));//调用翻转函数,翻转每一个单词
        return temp;
    }
    public static String reverseword(String word)//完全翻转单词函数
    {
        String result="";
        for(int i=word.length()-1;i>=0;i--)
        {
            result+=word.charAt(i);
        }
        return result;
    }
}
原文地址:https://www.cnblogs.com/zhangfanxmian/p/6803707.html