Problem
Reverse Words in a String II
Given an input string , reverse the string word by word.
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"]
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?
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--; } } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/69258.html
摘要:代碼先反轉(zhuǎn)整個(gè)數(shù)組反轉(zhuǎn)每個(gè)單詞雙指針交換法復(fù)雜度時(shí)間空間思路這題就是版的做法了,先反轉(zhuǎn)整個(gè)數(shù)組,再對(duì)每個(gè)詞反轉(zhuǎn)。 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...
摘要:一題目描述空格分隔,逐個(gè)反轉(zhuǎn)二題目描述三題目描述當(dāng)然也可以用的做,不過(guò)用雙指針更快。 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...
摘要:思路先用將字符串分割,再遍歷,將字符串內(nèi)每個(gè)單詞進(jìn)行翻轉(zhuǎn)代碼題意給定一個(gè)字符串,將字符串按照翻轉(zhuǎn),不翻轉(zhuǎn)的規(guī)則進(jìn)行處理。思路先將字符串分段,然后再根據(jù)段落進(jìn)行處理最后將字符串輸出。 344 Reverse String題意:給出一個(gè)字符串對(duì)字符串進(jìn)行翻轉(zhuǎn)(reverse)思路:直接使用切片函數(shù)進(jìn)行翻轉(zhuǎn)(網(wǎng)上看到的,具體怎么使用有點(diǎn)迷)[::-1]代碼:`class Solution(...
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...
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 ...
閱讀 1259·2021-10-11 10:57
閱讀 2045·2021-09-02 15:15
閱讀 1607·2019-08-30 15:56
閱讀 1195·2019-08-30 15:55
閱讀 1157·2019-08-30 15:44
閱讀 977·2019-08-29 12:20
閱讀 1321·2019-08-29 11:12
閱讀 1066·2019-08-28 18:29