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. 一些带dga域名的恶意软件

    04/02/2019 06:17下午 6,488,759 f4f242a50ba9efa1593beba6208a2508_PWS.win32.Simda_1250_DGADNS.pcap Simda ...

  2. [POJ2083] Fracal

    Description A fractal is an object or quantity that displays self-similarity, in a somewhat technica ...

  3. AT2000 Leftmost Ball

    设\(f[i][j]\)表示当前有\(i\)个白球,一共放完了\(j\)种球 显然有\(j <= i\) 对于每个状态目前已经放下去的球是固定了的,那么考虑转移 放白球 从\(f[i - 1][ ...

  4. python iter()函数迭代器

    迭代器为类序列对象提供了一个类序列的接口.python的迭代无缝地支持序列对象,而且它还允许程序员迭代非序列类型,包括用户定义的对象.迭代器用起来很灵巧,你可以迭代不是序列但表现处序列行为的对象,例如 ...

  5. 08.vue-router动态路由匹配

    动态匹配路由的基本用法 思考: <!-有如下3个路由链接.-> <router-link to="/user/1">User1</router-lin ...

  6. 项目集成Spring Security

    前言 之前写的 涂涂影院管理系统 这个 demo 是基于 shiro 来鉴权的,项目前后端分离后,显然集成 Spring Security 更加方便一些,毕竟,都用 Spring 了,权限管理当然 S ...

  7. LeetCode 787. Cheapest Flights Within K Stops

    原题链接在这里:https://leetcode.com/problems/cheapest-flights-within-k-stops/ 题目: There are n cities connec ...

  8. Redis存储Sortedset

    与set相比Sortedset多了一个数字与set中的各个元素相关联. 存储结构: 1.添加元素: 添加元素的时候元素一定不能相同,如果已存在该元素,表示插入失败返回0,成功返回1,但是不同元素的数字 ...

  9. Debian 9 安装 libsodium

    到这里查看最新的版本号.如现在最新的版本号为1.0.18.下面均以该版本为例. 下载.编译和安装: wget https://download.libsodium.org/libsodium/rele ...

  10. Maven 打包报错,log4j版本导致

    # 在执行打包的时候 mvn clean assembly:assembly # 发生上面的错误 ------------------------------ [INFO] Total time: 2 ...