zoukankan      html  css  js  c++  java
  • 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


  • 相关阅读:
    idea 相关
    dns 相关
    bash 相关
    建造者模式(Builder)
    C#中out 及 ref 区别
    C# 2.0新特性
    Asp.net.Ajax控件学习
    装饰模式(Decorator Pattern)
    职责链模式(Chain of Responsibility Pattern)
    面向对象
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13833170.html
Copyright © 2011-2022 走看看