zoukankan      html  css  js  c++  java
  • Leetcode: 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".
    
    click to show clarification.
    
    Clarification:
    What constitutes a word?
    A sequence of non-space characters constitutes a word.
    Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
    How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.

    这道题很直接的想法就是用String的split函数,把字符串按空格分成一个个子字符串,存到一个String[] strs里面,这时再把strs里的字符串从大到小反转连接,中间加上空格就好了。需要注意如果原来的字符串有multiple spaces, 那会造成我们strs数组里面有一些子字符串是空字符串,我们反转时若遇到这些空字符串,就要把它跳过。时间上split操作是O(N),再一次扫描获得结果,也是O(N)。空间上使用了一个String[] 和StringBuffer,也是O(N)

    本题就是需要注意一些语法,比如split函数的参数是String而不能是Char。我写的时候不小心再一次犯了低级错误,String判断是不是空字符串一定不要写成if (str == ""), 要么用equals(), 要么用length()==0来判断

    注意 split()函数argument是一个string而不是char

     1 public class Solution {
     2     public String reverseWords(String s) {
     3         if (s==null || s.length()==0) return s;
     4         s.trim();
     5         String[] strs = s.split(" ");
     6         StringBuffer res = new StringBuffer();
     7         for (int i=strs.length-1; i>=0; i--) {
     8             if (strs[i].length() == 0) continue;
     9             res.append(strs[i]);
    10             res.append(' ');
    11         }
    12         return res.toString().trim();
    13     }
    14 }
  • 相关阅读:
    SVN——Jenkins自动发布
    IIS之虚拟目录学习
    SVN迁移
    通过配置host,自定义域名让本地访问
    比较两个时间的大小 举例:CompareDate("12:00","11:15")
    [转]SQL Server 批量完整备份
    js前台编码,asp.net后台解码 防止前台传值到后台为乱码
    前端将图片二进制流显示在html端
    【转】解析<button>和<input type="button"> 的区别
    利用bat批处理——实现数据库的自动备份和删除
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/4019970.html
Copyright © 2011-2022 走看看