[LeetCode] Reverse Words in a String
来源:互联网 发布:cbox网络电视去广告版 编辑:程序博客网 时间:2024/06/08 02:04
题目
Given an input string, reverse the string word by word.
给定一个输入字符串,逐个单词地翻转字符串。
For example,
Given s = “the sky is blue
“,
return “blue is sky the
“.
分析
最直观的的思路是先将字符串中单词反转,再将整个字符串翻转。这样的思路没有问题,但要考虑到多余空格。
思路
- 处理字符串前后多余空格。
- 遍历字符串剩余字符串,用单词填补空格,并将其翻转。
- 处理字符串中多余空白:翻转单词后,添加一个空格,遇到其他空格直接忽略。
- 调整字符串大小,翻转整个字符串。
代码
#include <iostream>#include <string>using namespace std;class Solution {public: void reverseWord(string &s, int start, int end) { while (start < end) { char temp = s[start]; s[start++] = s[end]; s[end--] = temp; } } void reverseWords(string &s) { int start = 0, copy = 0; int length = s.length(); int leftSpaces = 0, rightSpaces = 0; for (int i = 0; i < length; i++) { if (s[i] != ' ') { break; } else { leftSpaces++; } } if (leftSpaces == length) { s = ""; return ; } for (int j = length - 1; j > 0; j--) { if (s[j] != ' ') { break; } else { rightSpaces++; } } for (int i = leftSpaces; i < length - rightSpaces;) { start = copy; while (i < length - rightSpaces && s[i] != ' ') { s[copy++] = s[i++]; } reverseWord(s, start, copy - 1); if (i < length - rightSpaces && copy > 0) { s[copy++] = ' '; } while (i < length - rightSpaces && s[i] == ' ') { i++; } } s.resize(copy); reverseWord(s, 0, copy - 1); }};int main() { Solution solution; string s = " abc efg "; cout << "Result:" << s << "(start)"<<endl; solution.reverseWords(s); cout << "Result:" << s << "(end)"<<endl; }
阅读全文
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
- 背包九讲
- UNP 基于Epoll复用的回射服务器性能测试
- AngularJs:Service、Factory、Provider依赖注入使用与区别
- iOS绘图框架CoreGraphics分析
- pageX、pageY及父元素的页面坐标使提示框跟随鼠标移动
- [LeetCode] Reverse Words in a String
- 关于BigDecimal类型在jsp页面中进行除法运算问题
- Selenium元素定位
- 数据结构--线索二叉树
- Hdu1069-Monkey and Banana
- Android自定义Dialog
- Swift_学习笔记_类
- Android进阶之路
- 1,key 的问题