• [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 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.

    算法思路:

    栈。(当然也可以逆序,就不需要借助栈了)

    代码如下:

     1 public class Solution {
     2     public String reverseWords(String s) {
     3         if(s == null || s.trim().length() == 0) return "";
     4         Stack<String> stack = new Stack<String>();
     5         s = s.trim();
     6         int start = 0,i = 0;
     7         for(; i < s.length(); i++){
     8             if(s.charAt(i) == ' '){
     9                 String word = s.substring(start, i);
    10                 stack.add(word);
    11                 while(s.charAt(i) == ' ') i++;
    12                 start = i;
    13             }
    14         }
    15         stack.add(s.substring(start, i));
    16         StringBuilder sb = new StringBuilder();
    17         while(!stack.isEmpty()){
    18             sb.append(stack.pop());
    19             sb.append(' ');
    20         }
    21         return sb.toString().trim();
    22     }
    23 }

    第二遍:

    真真是好久没刷了,连trim方法都不会用了,囧,这一次,感觉s.substring()效率太低,试图用sb逐个append,但是想了想,感觉略蛋疼,还是一个一个截吧,这次采取的是StringBuilder中的insert方法,不再需要借助栈了。

    代码如下:

     1 public class Solution {
     2     public String reverseWords(String s) {
     3         if(s == null || s.length() == 0) return "";
     4         int start = 0, end = 0;
     5         StringBuilder sb = new StringBuilder();
     6         for(int i = 0; i < s.length(); i++){
     7             while(i < s.length() && s.charAt(i) == ' ') i++;
     8             start = i;
     9             while(i < s.length() && s.charAt(i) != ' ') i++;
    10             if(start == i) continue;
    11             sb.insert(0," ");
    12             sb.insert(0, s.substring(start,i));
    13         }
    14         return sb.toString().trim();
    15     }
    16 }
  • 相关阅读:
    录音 静音检测
    Busybox是什么?
    ubuntu 和VMWare共享数据时故障解决
    使用IStream和GDI+在内存中实现图像格式转换
    .Net 玩自动化测试
    【C#|.NET】跳出一致性Hash算法 打造更高效的分布式缓存
    【C#|.NET】从细节出发(一) 通用接口 aop dto 相关
    【linux+C】神器 vim + 指针相关客串
    【C#|.NET】分布式锁服务
    读书笔记: CLR篇 (让你了解C#.Net的实质) (20111219更新)
  • 原文地址:https://www.cnblogs.com/huntfor/p/3864378.html
Copyright © 2020-2023  润新知