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--; } } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/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 ...
阅读 1239·2021-10-11 10:57
阅读 2026·2021-09-02 15:15
阅读 1567·2019-08-30 15:56
阅读 1174·2019-08-30 15:55
阅读 1138·2019-08-30 15:44
阅读 960·2019-08-29 12:20
阅读 1277·2019-08-29 11:12
阅读 1044·2019-08-28 18:29