[LeetCode] 151. 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 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 翻转字符串中的单词的更多相关文章
- [LeetCode] Reverse Words in a String 翻转字符串中的单词
Given an input string, reverse the string word by word. For example, Given s = "the sky is blue ...
- 【LeetCode】151. Reverse Words in a String 翻转字符串里的单词(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.co ...
- 151 Reverse Words in a String 翻转字符串里的单词
给定一个字符串,翻转字符串中的每个单词.例如,给定 s = "the sky is blue",返回 "blue is sky the".对于C程序员:请尝试用 ...
- [LintCode] Reverse Words in a String 翻转字符串中的单词
Given an input string, reverse the string word by word. For example,Given s = "the sky is blue& ...
- 【LeetCode】Reverse Words in a String 反转字符串中的单词
一年没有管理博客园了,说来实在惭愧.. 最近开始刷LeetCode,之前没刷过,说来也实在惭愧... 刚开始按 AC Rates 从简单到难刷,觉得略无聊,就决定按 Add Date 刷,以后也可能看 ...
- 151. Reverse Words in a String翻转一句话中的单词
[抄题]: Given an input string, reverse the string word by word. Example: Input: "the sky is blue& ...
- [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 ...
- Leetcode151. Reverse Words in a String翻转字符串里的单词
给定一个字符串,逐个翻转字符串中的每个单词. 示例: 输入: "the sky is blue", 输出: "blue is sky the". 说明: 无空格 ...
- [leetcode]151. Reverse Words in a String翻转给定字符串中的单词
Given an input string, reverse the string word by word. Example: Input: "the sky is blue", ...
随机推荐
- Improving Sequential Recommendation with Knowledge-Enhanced Memory Networks(知识图谱)
本文作者:杨昆霖,2015级本科生,目前研究方向为知识图谱,推荐系统,来自中国人民大学大数据管理与分析方法研究北京市重点实验室. 引言 经常上购物网站时,注意力会被首页上的推荐吸引过去,往往本来只想买 ...
- 正式一点的my.cnf文件
感觉比以前的文件,配置正式了一些. 留照. [client] port #socket=/mysql/mysql.sock default-character-set=utf8 [mysqld] po ...
- Celery(异步任务,定时任务,周期任务)
1.什么是Celery Celery是基于Python实现的模块,用于异步.定时.周期任务的. 组成结构: 1.用户任务 app 2.管道broker 用于存储任务 官方推荐 redis/rabbit ...
- Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'qingmu' for key 'PRIMARY'
### Error updating database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolatio ...
- Python库资源大全【收藏】
本文是一个精心设计的Python框架.库.软件和资源列表,是一个Awesome XXX系列的资源整理,由BigQuant整理加工而成,欢迎扩散.欢迎补充! 对机器学习.深度学习在量化投资中应用感兴趣的 ...
- SQL操作Spark SQL--CatalogApiTest
object CatalogApiTest { def main(args: Array[String]): Unit = { val spark = SparkSession .builder() ...
- LeetCode 1046. Last Stone Weight
原题链接在这里:https://leetcode.com/problems/last-stone-weight/ 题目: We have a collection of rocks, each roc ...
- MongoDB 4.2 新特性解读 (转载)
MongoDB World 2019 上发布新版本 MongoDB 4.2 Beta,包含多项数据库新特性,本文尝试从技术角度解读. Full Text Search MongoDB 4.2 之前,全 ...
- svn服务的安装与设置 .
1. 下载svn软件并安装,本人使用的是如下软件: TortoiseSVN-1.6.5.16974-win32-svn-1.6.5 Vis ...
- Thread线程框架学习
原文:https://www.cnblogs.com/wangkeqin/p/9351299.html Thread线程框架 线程定义:线程可以理解为一个特立独行的函数.其存在的意义,就是并行,避免了 ...