Leetcode-Reverse Words in a String
2018-01-22 20:38
225 查看
Given an input string, reverse the string word by word.
For example,
Given s = "
return "
1. substr(pos,len)
2. 字符串中连续的多个空格被当作一个空格
pos每次指向一个单词的第一个字符,如果i==pos说明字符串开头有空格,pos=i+1就能跳过开头的空格
3.字符串最后一个单词可能没有空格,需要单独处理
4.思想类似于“头插法”
每次取一个单词,然后将上一次得到的子串连在新单词后面,就实现了单词顺序反转。
参考a solution from Leetcode:https://discuss.leetcode.com/topic/3087/accepted-simple-cpp-code-in-just-a-few-lines
For example,
Given s = "
the sky is blue",
return "
blue is sky the".
void reverseWords(string &s) { int pos = 0; string res; for (int i = 0; i != s.size(); i++) { if (s[i] == ' ') { if (i > pos) { //a word res = s.substr(pos, i - pos) + " " + res; } pos = i + 1;//next word } else if (i == s.size() - 1) {//last word size=1 res = s.substr(pos, s.size() - pos) + " " + res; } } s = res.substr(0, res.size()-1); }notes:
1. substr(pos,len)
2. 字符串中连续的多个空格被当作一个空格
pos每次指向一个单词的第一个字符,如果i==pos说明字符串开头有空格,pos=i+1就能跳过开头的空格
3.字符串最后一个单词可能没有空格,需要单独处理
4.思想类似于“头插法”
每次取一个单词,然后将上一次得到的子串连在新单词后面,就实现了单词顺序反转。
参考a solution from Leetcode:https://discuss.leetcode.com/topic/3087/accepted-simple-cpp-code-in-just-a-few-lines
相关文章推荐
- [Leetcode刷题]Reverse Words in a String
- Leetcode之Reverse Words in a String
- [LeetCode 151] Reverse Words in a String
- leetcode-reverse words in a string
- LeetCode Reverse Words in a String
- [leetcode] Reverse Words in a String
- Leetcode 151题 Reverse Words in a String
- LeetCode *** 151. Reverse Words in a String
- Reverse words in a String leetcode
- leetcode 151. Reverse Words in a String
- [LeetCode]Reverse Words in a String
- Reverse Words in a String (LeetCode)
- [leetCode]Reverse Words in a String
- leetcode-Reverse Words in a String
- [LeetCode]Reverse Words in a String
- 【leetcode】 Reverse Words in a String
- LeetCode刷题笔录Reverse Words in a String
- [leetcode]151. Reverse Words in a String@Java解题报告
- [Leetcode] Reverse Words in a String
- 【Leetcode】:Reverse-Words-in-a-String