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

  • 相关阅读:
    2016年 河南工业大学校赛 D题.rqy的键盘
    2016年 河南工业大学校赛 C题.魔法宝石
    jqueryMobile导航
    jqueryMobile列表
    jqueryMobile
    停止css3动画
    导航条
    移动端前面必须加的两行代码
    标签页
    file上传图片预览(此方法支持app)
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6363911.html
Copyright © 2011-2022 走看看