码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 557. Reverse Words in a String III

时间:2017-08-31 21:10:01      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:bug   single   stat   .com   res   解释   void   一点   i++   

晚饭后写了一题。当然,我这种菜鸟是从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

标签:bug   single   stat   .com   res   解释   void   一点   i++   

原文地址:http://www.cnblogs.com/yeyeck/p/7460383.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!