资讯专栏INFORMATION COLUMN

Reverse Words in a String

keelii / 923人阅读

摘要:思路把以空格为间隔分隔开存入然后倒着加入并且每个加入以后后面加空格,最后记的清除最后一个空格。

Reverse Words in a String

Given an input string, reverse the string word by word.

For example, Given s = "the sky is blue", return "blue is sky the".

思路: 把string以空格为间隔分隔开存入array, 然后倒着加入stringBuilder并且每个加入以后后面加空格,最后记的清除最后一个空格。

public class Solution {
   public String reverseWords(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }

        String[] array = s.split(" ");
        StringBuilder sb = new StringBuilder();

        for (int i = array.length - 1; i >= 0; i--) {
            if (!array[i].equals("")) {
                sb.append(array[i]).append(" ");
            }
        }

        //remove the last " "
        return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/64797.html

相关文章

  • [Leetcode] Reverse Words in a String 反转单词顺序

    摘要:代码先反转整个数组反转每个单词双指针交换法复杂度时间空间思路这题就是版的做法了,先反转整个数组,再对每个词反转。 Reverse Words in a String Given an input string, reverse the string word by word. For example, Given s = the sky is blue, return blue is...

    codeKK 评论0 收藏0
  • [LeetCode] Reverse Words in a String II

    Problem Reverse Words in a String IIGiven an input string , reverse the string word by word. Example Input: [t,h,e, ,s,k,y, ,i,s, ,b,l,u,e]Output: [b,l,u,e, ,i,s, ,s,k,y, ,t,h,e] Note A word is defin...

    浠ラ箍 评论0 收藏0
  • [LeetCode] 557. Reverse Words in a String III

    Problem 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: Lets take LeetCode contest...

    104828720 评论0 收藏0
  • Leetcode PHP题解--D20 557. Reverse Words in a String

    摘要:题目链接题目分析题目要求把句子中的每个单词都倒转过来。思路这个很简单,用空格把句子分割,再用把字符串倒转过来,拼接起来就可以了。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 557. Reverse Words in a String III 题目链接 557. Reverse Words in a String III 题目分析 题目要求把句子中的每个单词都倒转过来。 思路 这个...

    LoftySoul 评论0 收藏0
  • leetcode 151. Reverse Words in a String

    摘要:题目要求讲一个字符串中的单词逆序输出,单词中字母顺序不发生改变。其中,字符串首位的空格应删去,字符串中如果存在多余的空格,只需输出一个空格。这里用到的正则表达式为也就是遇到一个或多个空白时断句。 题目要求 Given an input string, reverse the string word by word. For example, Given s = the sky is ...

    yzd 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<