1. 程式人生 > >LeetCode 557. Reverse Words in a String III

LeetCode 557. Reverse Words in a String III

sys etc extra tel ted spl rgs leet word

晚飯後寫了一題。當然,我這種菜鳥是從easy開始寫的。。。發現leetcode也是有bug的

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.

題目我就不解釋了。。。都不用看題的。我這種菜鳥只能寫比較蛋疼的辦法。。。如下

public class Solution {
    public String reverseWords(String s) {
        String[] tokens = s.split("\t");
        StringBuffer strBuf = new StringBuffer();
        for(int i=0;i<tokens.length;i++)
        {
            tokens[i] = reverse(tokens[i]);
            
if(i==tokens.length-1) strBuf.append(tokens[i]); else strBuf.append(tokens[i]+" "); } return strBuf.toString(); } public String reverse(String s) { StringBuffer strBuf = new StringBuffer(); for(int i=0;i<s.length();i++) { strBuf
= strBuf.append(s.charAt(s.length()-1-i)); } return strBuf.toString(); } }

一跑,結果如下

技術分享

單詞的順序是反過來的。。。

於是我復制到Eclipse去跑

public class ReverseWords
{
    public static String reverse(String s)
    {
        StringBuffer strBuf = new StringBuffer();
        for(int i=0;i<s.length();i++)
        {
            strBuf = strBuf.append(s.charAt(s.length()-1-i));
        }
        return strBuf.toString();
    }
    

    public static void main(String[] args)
    {
        String str = "Let‘s take LeetCode contest";
        String[] tokens = str.split(" ");
        StringBuffer strBuf = new StringBuffer();
        for(int i=0;i<tokens.length;i++)
        {
            tokens[i] = reverse(tokens[i]);
            if(i==tokens.length-1)
                strBuf.append(tokens[i]);
            else strBuf.append(tokens[i]+" ");
        }
        System.out.println(strBuf.toString());

    }

}

技術分享

一點問題也沒有

LeetCode 557. Reverse Words in a String III