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--; } } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/69258.html
摘要:代碼先反轉整個數組反轉每個單詞雙指針交換法復雜度時間空間思路這題就是版的做法了,先反轉整個數組,再對每個詞反轉。 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...
摘要:一題目描述空格分隔,逐個反轉二題目描述三題目描述當然也可以用的做,不過用雙指針更快。 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...
摘要:思路先用將字符串分割,再遍歷,將字符串內每個單詞進行翻轉代碼題意給定一個字符串,將字符串按照翻轉,不翻轉的規則進行處理。思路先將字符串分段,然后再根據段落進行處理最后將字符串輸出。 344 Reverse String題意:給出一個字符串對字符串進行翻轉(reverse)思路:直接使用切片函數進行翻轉(網上看到的,具體怎么使用有點迷)[::-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 ...
閱讀 1279·2021-10-11 10:57
閱讀 2051·2021-09-02 15:15
閱讀 1613·2019-08-30 15:56
閱讀 1205·2019-08-30 15:55
閱讀 1163·2019-08-30 15:44
閱讀 985·2019-08-29 12:20
閱讀 1331·2019-08-29 11:12
閱讀 1073·2019-08-28 18:29