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是把字母顺序完全变换了。

  • 相关阅读:
    python 对比学习
    支付宝
    springboot logback
    ngnix学习视频
    node学习
    puppeteer 相关知识
    Dota2App--第三天
    Dota2APP--第二天
    Dota2APP--第一天
    iOS ---进阶之摇一摇
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6363911.html
Copyright © 2011-2022 走看看