LeetCode Reverse Words in a String II

原题链接在这里:https://leetcode.com/problems/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?

Related problem: Rotate Array

题解:

类似Reverse Words in a String. input变成 char array. 

先reverse 全部 char array. 从头往后走,遇到空格或者array尾部,就reverse中间的单词.

Time Compelxity: O(s.length()). Space: O(1).

AC Java:

 1 public class Solution {
 2     public void reverseWords(char[] s) {
 3         if(s == null || s.length == 0){
 4             return;
 5         }
 6         reverse(s, 0, s.length-1);
 7         
 8         int lo = 0;
 9         for(int i = 1; i<=s.length; i++){
10             if(i == s.length || s[i] == ' '){
11                 reverse(s, lo, i-1);
12                 lo = i+1;
13             }
14         }
15     }
16     
17     private void reverse(char [] s, int i, int j){
18         while(i < j){
19             swap(s, i++, j--);
20         }
21     }
22     
23     private void swap(char [] s, int i , int j){
24         char temp = s[i];
25         s[i] = s[j];
26         s[j] = temp;
27     }
28 }

跟上Reverse Words in a String III.

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/5246475.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值