zoukankan      html  css  js  c++  java
  • [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 }
  • 相关阅读:
    VirtualBox 全屏问题
    PHP中SQLite模块的加载
    Js选择器总结
    安全测试06常规软件的需要测试哪些方面?
    安全测试04kala Linux 局域网扫描IP进行断网攻击
    安全测试10nmap基本使用方法
    安全测试03kali Linux 长期获取ROO权限
    安全测试09DMitry域名查询工具
    MeterSphere自动化测试框架安装步骤
    安全测试05Wpscan扫描WordPress漏洞
  • 原文地址:https://www.cnblogs.com/huntfor/p/3864378.html
Copyright © 2011-2022 走看看