[LintCode] Reverse Words in a String 翻转字符串中的单词
string 字符串 in 单词 翻转 words lintcode reverse
2023-09-11 14:21:37 时间
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
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.
LeetCode上的原题,请参见我之前的博客Reverse Words in a String。
解法一:
class Solution { public: /** * @param s : A string * @return : A string */ string 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; } } return string(s.begin(), s.begin() + storeIndex); } };
解法二:
class Solution { public: /** * @param s : A string * @return : A string */ string reverseWords(string s) { string res = "", t = ""; istringstream is(s); while (getline(is, t, ' ')) { if (t.empty()) continue; res = (res.empty() ? t : (t + " " + res)); } return res; } };
解法三:
class Solution { public: /** * @param s : A string * @return : A string */ string reverseWords(string s) { istringstream is(s); is >> s; string t; while (is >> t) { s = t + " " + s; } return (s[0] == ' ') ? "" : s; } };
相关文章
- G面经prepare: Reorder String to make duplicates not consecutive
- Caused by: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'company' in 'class java.lang.String'
- java字符数组char[]和字符串String之间的转换
- Java数据类型—String进阶之字符串常量池
- Java数据类型—String基础
- python string 详解
- 【Java】String,StringBuffer与StringBuilder的区别??
- 【C++初阶】STL-string的使用
- JAVA字符串格式化-String.format()的使用 及 Android 中 string.xml 中 字符串格式转化
- JAVA字符串格式化-String.format()的使用
- JAVA String字符串截取、匹配
- 《String类常见的API》: 字符串的查询操作。
- C++中字符数组与string的相互转换
- linq查询结果datetime类型转string类型
- 【Java】:Java当中为什么不能够直接用==比较String字符串
- C# string数组转int数组(转载)
- [LeetCode] 1221. Split a String in Balanced Strings 分割平衡字符串
- [LeetCode] Number of Lines To Write String 写字符串需要的行数
- [LeetCode] Rotate String 旋转字符串
- [LeetCode] Reverse Words in a String III 翻转字符串中的单词之三
- [LeetCode] Reverse String II 翻转字符串之二
- [LeetCode] 438. Find All Anagrams in a String 找出字符串中所有的变位词
- [LeetCode] 471. Encode String with Shortest Length 最短长度编码字符串
- [LeetCode] Unique Substrings in Wraparound String 封装字符串中的独特子字符串
- [CareerCup] 1.5 Compress String 压缩字符串
- Redis学习系列二之.Net开发环境搭建及基础数据结构String字符串
- 字符、字符串和文本的处理之String类型
- Redis学习03——存储字符串(String)
- String templates are not supported by current javaScript version