zoukankan      html  css  js  c++  java
  • Reverse Words in a String II

    Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.

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

    For example,
    Given s = "the sky is blue",
    return "blue is sky the".

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

    先把每个词反转一遍, 再把整个string 反转一遍。

     1 public class Solution {
     2     public void reverseWords(char[] s) {
     3         for(int i = 0, j = 0; j <= s.length && i < s.length; j ++){
     4             if(j == s.length || s[j] == ' '){
     5                 reverse(s, i, j - 1);
     6                 i = j + 1;
     7             }
     8         }
     9         reverse(s, 0, s.length - 1);
    10     }
    11     
    12     private void reverse(char[] c, int s, int e){
    13         while(s < e){
    14             char tmp = c[s];
    15             c[s] = c[e];
    16             c[e] = tmp;
    17             s ++; e --;
    18         }
    19     }
    20 }
  • 相关阅读:
    个人阅读2
    代码复审
    PairProject 总结
    Pairproject 移山之道 阅读随笔和一些问题
    M1/M2个人总结
    团队项目个人总结
    个人阅读作业2
    代码互审
    《移山之道》读后感
    Individual Project
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/4277374.html
Copyright © 2011-2022 走看看