国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

[LeetCode] Reverse Words in a String II

浠ラ箍 / 1397人閱讀

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://m.specialneedsforspecialkids.com/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元查看
<