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

    Update (2015-02-12):
    For C programmers: Try to solve it in-place in O(1) space.

    此题要注意裁剪空格。代码如下:

    public class Solution {

        public String reverseWords(String s) {

            String[] str = s.trim().split("\s+");

            int left = 0;

            int right = str.length-1;

            while(left<right){

                String temp = str[left];

                str[left] = str[right];

                str[right] = temp;

                left++;

                right--;

            }

            StringBuilder sb = new StringBuilder();

            for(int i=0;i<str.length;i++){

                if(i==str.length-1){

                    sb.append(str[i]);

                }else{

                    sb.append(str[i]+" ");

                }

            }

            return sb.toString();

        }

    }

    我开始的时候想能不能用reverse来做,后来发现不行,reverse是把字母顺序完全变换了。

  • 相关阅读:
    react组件销毁中清理异步操作和取消请求
    只要一行代码,实现五种 CSS 经典布局
    vue中如何安装sass,sass安装命令
    每日总结
    每日总结
    每日总结
    每周总结
    每日总结
    每日总结
    每日总结
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6363911.html
Copyright © 2011-2022 走看看