资讯专栏INFORMATION COLUMN

[LeetCode] Reverse Words in a String II

浠ラ箍 / 1373人阅读

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--;
        }
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/69258.html

相关文章

  • [Leetcode] Reverse Words in a String 反转单词顺序

    摘要:代码先反转整个数组反转每个单词双指针交换法复杂度时间空间思路这题就是版的做法了,先反转整个数组,再对每个词反转。 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...

    codeKK 评论0 收藏0
  • 翻转字符串的相关题目

    摘要:一题目描述空格分隔,逐个反转二题目描述三题目描述当然也可以用的做,不过用双指针更快。 LeetCode: 557. Reverse Words in a String III 一、LeetCode: 557. Reverse Words in a String III 题目描述 Given a string, you need to reverse the order of chara...

    lykops 评论0 收藏0
  • leetcode刷题笔记(2)(python)

    摘要:思路先用将字符串分割,再遍历,将字符串内每个单词进行翻转代码题意给定一个字符串,将字符串按照翻转,不翻转的规则进行处理。思路先将字符串分段,然后再根据段落进行处理最后将字符串输出。 344 Reverse String题意:给出一个字符串对字符串进行翻转(reverse)思路:直接使用切片函数进行翻转(网上看到的,具体怎么使用有点迷)[::-1]代码:`class Solution(...

    Guakin_Huang 评论0 收藏0
  • [LeetCode] 244. Shortest Word Distance II

    Problem Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the l...

    Nekron 评论0 收藏0
  • [LeetCode] 445. Add Two Numbers II

    Problem You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and ...

    alexnevsky 评论0 收藏0

发表评论

0条评论

浠ラ箍

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<