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".

    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.

    https://oj.leetcode.com/problems/reverse-words-in-a-string/

    思路:用split方法分割后倒序遍历加入结果中即可。

    /**
     * http://blog.csdn.net/perfect8886/article/details/20833685
     * 
     * */
    public class Solution {
        public String reverseWords(String s) {
            String[] a = s.split(" ");
            StringBuilder sb = new StringBuilder();
            for (int i = a.length - 1; i >= 0; i--) {
                if (!a[i].equals("")) {
                    sb.append(a[i]);
                    sb.append(" ");
                }
            }
            if (sb.length() > 1)
                sb.deleteCharAt(sb.length() - 1);
    
            return sb.toString();
        }
    
        public static void main(String[] args) {
            System.out.println(new Solution().reverseWords("the sky is blue"));
        }
    
    }

    第二遍记录:

    注意split方法可能产生“”,需要判断处理下。

    复习1

    手工实现类似split的功能,从后向前遍历解析出word塞到StringBuilder中即可。注意如何判断一个word的开头和结束。

    public class Solution {
        public String reverseWords(String s) {
            StringBuilder sb = new StringBuilder();
            int i = s.length()-1;
            int j = s.length();
            for(;i>=0;i--){
                if(s.charAt(i)==' '){
                    j = i;
                }else{
                    if(i==0 || s.charAt(i-1)==' '){
                        if(sb.length()!=0){
                            sb.append(" ");
                        }
                        sb.append(s.substring(i,j));
                    }
                }
            }
            return sb.toString();
        }
    }
    

      

    Follow Up:  Reverse Words in a String II 

    Question: 

    Similar to Question [6. Reverse Words in a String], but with the following constraints:

    “The input string does not contain leading or trailing spaces and the words are always separated by a single space.”

    Could you do it in-place without allocating extra space? 

  • 相关阅读:
    大厂的面试官是如何挑人的?
    搞懂这7个Maven问题,带你吊打面试官!
    Spring Cloud Eureka 注册安全一定要做到位!
    09 webpack的介绍
    08 node.js 的使用
    07 Node.js安装及环境配置
    06-Nodejs介绍
    05-面向对象
    Mysql 的使用方法
    04-对象的单体模式
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3830538.html
Copyright © 2011-2022 走看看