Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

Clarification:

  • What constitutes a word?
  • A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
  • Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
  • Reduce them to a single space in the reversed string.

把一个字符串中的单词逆序,单词字符顺序不变。

解法1: New array, 新建一个数组,把字符串以空格拆分成单词存到数组,在把单词逆序拷贝进新数组。

解法2: One place,不能新建数组,在原数组的基础上换位。把字符串的所以字符逆序,然后在把每个单词的字符逆序。

Java: New array, two pass

public String reverseWords(String s) {
String[] words = s.trim().split("\\s+");
if(words.length == 0) {
return "";
}
StringBuilder sb = new StringBuilder(words[words.length-1]);
for(int i=words.length-2; i >=0; i--) {
sb.append(" "+words[i]);
}
return sb.toString();
}

Java: New array, one pass

public String reverseWords(String s) {
StringBuilder sb = new StringBuilder();
int end = s.length();
int i = end-1;
while(i>=0) {
if(s.charAt(i) == ' ') {
if(i < end-1) {
sb.append(s.substring(i+1, end)).append(" ");
}
end = i;
}
i--;
}
sb.append(s.substring(i+1, end));
return sb.toString().trim();
}

Java: New array, one pass

public String reverseWords(String s) {
StringBuilder sb = new StringBuilder();
int last = s.length();
for(int i=s.length()-1; i>=-1; i--) {
if(i==-1 || s.charAt(i)==' ') {
String word = s.substring(i+1, last);
if(!word.isEmpty()) {
if(sb.length() != 0) sb.append(' ');
sb.append(word);
}
last = i;
}
}
return sb.toString();
}

Java:One place

public String reverseWords(String s) {
if(s == null || s.isEmpty()) return s;
char[] data = s.toChartArray();
int n = data.length;
reverse(data, 0, n-1); int last = -1;
for(int i=0; i<=n; i++) {
if(i == n || data[i] == ' ') {
if(i-last>1) reverse(data, last+1, i-1);
last = i;
}
} return new String(data);
} private void reverse(char[] data, int start, int end) {
while(start < end) {
char tmp = data[start];
data[start++] = data[end];
data[end--] = tmp;
}
}

Python: New array

class Solution:
# @param s, a string
# @return a string
def reverseWords(self, s):
return ' '.join(reversed(s.split()))

C++:

class Solution {
public:
void reverseWords(string &s) {
int storeIndex = 0, n = s.size();
reverse(s.begin(), s.end());
for (int i = 0; i < n; ++i) {
if (s[i] != ' ') {
if (storeIndex != 0) s[storeIndex++] = ' ';
int j = i;
while (j < n && s[j] != ' ') s[storeIndex++] = s[j++];
reverse(s.begin() + storeIndex - (j - i), s.begin() + storeIndex);
i = j;
}
}
s.resize(storeIndex);
}
};

类似题目:

[LeetCode] 186. Reverse Words in a String II 翻转字符串中的单词 II

[LeetCode] 557. Reverse Words in a String III 翻转字符串中的单词 III  

All LeetCode Questions List 题目汇总

  

  

  

  

[LeetCode] 151. Reverse Words in a String 翻转字符串中的单词的更多相关文章

  1. [LeetCode] Reverse Words in a String 翻转字符串中的单词

    Given an input string, reverse the string word by word. For example, Given s = "the sky is blue ...

  2. 【LeetCode】151. Reverse Words in a String 翻转字符串里的单词(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.co ...

  3. 151 Reverse Words in a String 翻转字符串里的单词

    给定一个字符串,翻转字符串中的每个单词.例如,给定 s = "the sky is blue",返回 "blue is sky the".对于C程序员:请尝试用 ...

  4. [LintCode] Reverse Words in a String 翻转字符串中的单词

    Given an input string, reverse the string word by word. For example,Given s = "the sky is blue& ...

  5. 【LeetCode】Reverse Words in a String 反转字符串中的单词

    一年没有管理博客园了,说来实在惭愧.. 最近开始刷LeetCode,之前没刷过,说来也实在惭愧... 刚开始按 AC Rates 从简单到难刷,觉得略无聊,就决定按 Add Date 刷,以后也可能看 ...

  6. 151. Reverse Words in a String翻转一句话中的单词

    [抄题]: Given an input string, reverse the string word by word. Example: Input: "the sky is blue& ...

  7. [LeetCode] Reverse Vowels of a String 翻转字符串中的元音字母

    Write a function that takes a string as input and reverse only the vowels of a string. Example 1:Giv ...

  8. Leetcode151. Reverse Words in a String翻转字符串里的单词

    给定一个字符串,逐个翻转字符串中的每个单词. 示例: 输入: "the sky is blue", 输出: "blue is sky the". 说明: 无空格 ...

  9. [leetcode]151. Reverse Words in a String翻转给定字符串中的单词

    Given an input string, reverse the string word by word. Example: Input: "the sky is blue", ...

随机推荐

  1. Mysql【第三课】

  2. js 预解析以及变量的提升

    js在执行之前会进行预解析. 什么叫预解析? 预:提前 解析:编译 预解析通俗的说:js在执行代码之前会读取js代码,会将变量声明提前. 变量声明包含什么?1.var 声明 2.函数的显示声明. 提前 ...

  3. jmeter设置代理服务器录制脚本

    新建测试计划之后: 1.添加非测试元件:HTTP代理服务器 a.其中目标控制器可以控制选哪个线程放录制的脚本: b.将端口设置为8888或者其他不常用的端口,保持跟其他应用的端口不一致,否则被占用导致 ...

  4. Linux安装部署项目实例

    本次安装jdk,mysql,maven,redis,nginx,tomcat 安装之前先升级系统 使用命令:/bin/yum - y update 1.安装jdk 先建立一个项目的目录-jiaoton ...

  5. MySQL——查询优化|47s到0.1s|我做了什么

    前言 这个代码是之前的同事写的,现在我接管了,但是今天早上我打开这个模块的时候发现数据加载异常的缓慢,等了将近一分钟左右数据才显示到页面. 这特么的绝对不正常啊,数据量压根没那么多呀,这特喵的什么情况 ...

  6. Spark-源码分析02-Luanch Executor

    1.SparkContext.scala sparkcontext 在被new的时候,会执行class中的代码 其中有一个就是创建TaskScheduler 和 SchedulerBackend,而S ...

  7. 使用jmx-exporter&&jmxtrans && nexus jmx 暴露nexus 系统指标信息

    以下演示一个简单的使用jmxexporter 暴露nexus jmx 指标为prometheus metrics,同时也集成了一个简单的jmxtrans 输出数据到 graphite 环境准备 doc ...

  8. 一些常用的文本文件格式(TXT,JSON,CSV)以及如何从这些文件中读取和写入数据

    TXT文件: txt是微软在操作系统上附带的一种文本格式,文件以.txt为后缀. 从txt文件中读取数据: with open ('xxx.txt') as file: data=file.readl ...

  9. javascript 之正则表达式匹配不包含特定字符串的字符

    如:有如下字符串,想查出不包含min.js的字符串  ['xx.min.js','xx.js','x.js','x.min.js'] 方法一: 使用逻辑非判断, !/min\.js/.test(str ...

  10. uwsgi example

    ref   (uwsgi unix socket example) cat /etc/os-release curl --version # curl sudo pip install uwsgi e ...