LeetCode 557. Reverse Words in a String III
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 557. Reverse Words in a String III相关的知识,希望对你有一定的参考价值。
晚饭后写了一题。当然,我这种菜鸟是从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的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode - 557. Reverse Words in a String III
LeetCode 557. Reverse Words in a String III
leetcode-557-Reverse Words in a String III
LeetCode 557. Reverse Words in a String III