博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Reverse Words in a String II
阅读量:5894 次
发布时间:2019-06-19

本文共 1163 字,大约阅读时间需要 3 分钟。

Problem

Reverse Words in a String II

Given an input string , reverse the string word by word.

Example

Input: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]

Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]

Note

A word is defined as a sequence of non-space characters.

The input string does not contain leading or trailing spaces.
The words are always separated by a single space.
Follow up: Could you do it in-place without allocating extra space?

Solution

class Solution {    public void reverseWords(char[] str) {        int start = 0, end = str.length-1;        //reverse all chars        reverse(str, start, end);        for (int i = 0; i < str.length; i++) {            //reverse all words back, except for the last one            if (str[i] == ' ') {                reverse(str, start, i-1);                start = i+1;            }        }        //reverse the last word back        reverse(str, start, end);    }    private void reverse(char[] str, int i, int j) {        while (i < j) {            char temp = str[i];            str[i] = str[j];            str[j] = temp;            i++;            j--;        }    }}

转载地址:http://stisx.baihongyu.com/

你可能感兴趣的文章
ssh 安装笔记
查看>>
游戏音效下载网站大全
查看>>
angular $resouse服务
查看>>
实验五
查看>>
文法分析
查看>>
记那次失败了的面试
查看>>
程序包+创建包规范+创建包体+删除程序包
查看>>
3-继承
查看>>
java中如何实现类似goto的作法
查看>>
海归千千万 为何再无钱学森
查看>>
vue2.0 仿手机新闻站(六)详情页制作
查看>>
FreeRTOS的内存管理
查看>>
JSP----九大内置对象
查看>>
The Z-Index CSS Property: A Comprehensive Look | Smashing Coding
查看>>
Java中HashMap详解
查看>>
Office版本差别引发的语法问题
查看>>
Apache——访问控制
查看>>
web前端(10)—— 浮动,清除默认样式
查看>>
ggplot2 aes函数map到data笔记
查看>>
3450: Tyvj1952 Easy
查看>>