• 151. Reverse Words in a String翻转一句话中的单词


    Given an input string s, reverse the order of the words.

    A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

    Return a string of the words in reverse order concatenated by a single space.

    Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

     

    Example 1:

    Input: s = "the sky is blue"
    Output: "blue is sky the"
    

    Example 2:

    Input: s = "  hello world  "
    Output: "world hello"
    Explanation: Your reversed string should not contain leading or trailing spaces.
    

    Example 3:

    Input: s = "a good   example"
    Output: "example good a"
    Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
    

    Example 4:

    Input: s = "  Bob    Loves  Alice   "
    Output: "Alice Loves Bob"

    思路:不用while (i < j),直接从最后一位开始倒贴就行了。这是一个好思路!

    光是split就行了,不用再加toarray。

    区别:toCharArray()是变成char array, split是变成string array
    String[] words = s.split("\s+");

    字符串连接:明明就只有+和concat(),StringBuildr sb才用append()

    class Solution {
        public String reverseWords(String s) {
            //cc
            if (s == null || s == "")
                return "";
            
            //分成words[]数组
            //光是split就行了,不用再变成array
            String[] words = s.split("\s+");
            String result = "";
            
            //倒贴
            for(int i = words.length - 1; i > 0; i--) {
                //字符串连接明明就只有+和concat(),StringBuildr sb才用append()
                result += words[i];
                result += " ";
            }
            
            result += words[0];
            
            return result;
        }
    }
    View Code


  • 相关阅读:
    Redis学习笔记——环境搭建
    SQL 记录
    路径“D:svn.....”的访问被拒绝问题处理
    去除浏览器自动给input赋值的问题
    获取用户IP
    JS对身份证号码进行验证方法
    JS 实现倒计时
    SQL 游标
    .net上传图片实例
    生成唯一码
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13833170.html
Copyright © 2020-2023  润新知