[LeetCode] Reverse Words in a String
来源:互联网 发布:淘宝免费活动大全 编辑:程序博客网 时间:2024/06/05 13:14
Given an input string, reverse the string word by word.
For example, Given s = "the sky is blue", return "blue is sky the".
Clarification:
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.
代码很简单:
从头向尾扫描s:
如果当前字符是space,而且buffer string 不为空,那么输出buffer string。
如果当前字符是space,而且buffer string为空,那么不输出buffer string。
如果当前字符不是space,那么把当前字符添加到buffer string。
class Solution {public: void reverseWords(string &s) { string word; //tmp string to store each word string res; // result string int i=0; while (i<s.size()){ if (char(s[i])==' ' && word.empty()){i++;continue;} //multiple spaces if (char(s[i])==' ' && !word.empty()){ //first space after a word res = word+" "+ res; //store the word word=""; //reset the word i++; continue; } if (char(s[i])!=' '){word=word+char(s[i]);i++; continue;} //non-space chars } if (!word.empty()){ //last word s = word+" "+res; }else{ s = res; } s = s.substr(0,s.size()-1); //eliminate the last space } };
0 0
- Leetcode - string - Reverse Words in a String
- Reverse words in a String leetcode
- [LeetCode]Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- Reverse Words in a String (LeetCode)
- LeetCode Reverse Words in a String Total
- LeetCode(151)Reverse Words in a String
- Reverse Words in a String -- LeetCode
- leetcode Reverse Words in a String
- LeetCode OJ:Reverse Words in a String
- LeetCode Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- [Leetcode] Reverse Words in a String
- Reverse Words in a String[LeetCode]
- LeetCode OJ :Reverse Words in a String
- Leetcode: Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- ofbiz邮件配置
- PHP垃圾回收机制的理解
- Android软件安全与逆向分析——Dalvik是如何执行程序的
- Windows下安装solr-4.10.3
- Android Studio中常用设置与快捷键
- [LeetCode] Reverse Words in a String
- 指针数组和数组指针的区别
- 二叉树建立出现的指针问题
- php清除不明输出(echo前面的回车换行符\t\n等)
- jsp的分页技术
- 3、php中变量、常量的命名规则及使用
- linux下重启mysql php nginx
- 数据结构----迷宫问题
- 8086CPU寄存器全称