LeetCode 541. Reverse String II (字符串翻转)
来源:互联网 发布:火炬之光 mac人物存档 编辑:程序博客网 时间:2024/06/06 20:22
Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.
Example:
Input: s = "abcdefg", k = 2Output: "bacdfeg"Restrictions:
- The string consists of lower English letters only.
- Length of the given string and k will in the range [1, 10000]
输入字符串s和正整数k,对于每2k个字母,将其中前k个字母翻转。最后如果剩余字母少于k个,则将其全部翻转;若多于k个,则将前k个翻转,其余不变。
思路:利用void reverse(str.begin(),str.end())函数直接原位翻转,若要翻转到其他变量,可使用str2.assign(str.rbegin(), str.rend())函数。
string reverseStr(string s, int k) { int left = s.size()%(2*k); int i; if (left<k) { for(i=0;i<s.size()-left;i+=(2*k)) reverse(s.begin()+i,s.begin()+i+k); reverse(s.begin()+i,s.end()); } else { for(i=0;i<s.size()-left;i+=(2*k)) reverse(s.begin()+i,s.begin()+i+k); reverse(s.begin()+i,s.begin()+i+k); } return s; }
阅读全文
0 0
- LeetCode 541. Reverse String II (字符串翻转)
- LeetCode 344. Reverse String(字符串翻转)
- 字符串-leetcode 541. Reverse String II
- leetcode 541. Reverse String II 反转字符串
- LeetCode 344: Reverse String (字符串翻转)
- Reverse String 翻转字符串
- leetcode 541. Reverse String II
- Leetcode-541. Reverse String II
- 【Leetcode】541. Reverse String II
- 541. Reverse String II LeetCode
- [LeetCode]541. Reverse String II
- LeetCode 541. Reverse String II
- LeetCode 541. Reverse String II
- leetcode-541. Reverse String II
- [leetcode]541. Reverse String II
- [leetcode]: 541. Reverse String II
- LeetCode:541. Reverse String II
- LeetCode 541. Reverse String II
- R语言数据结构
- Java设计模式——代理模式(Proxy Pattern)
- 学习淘淘商城第八十二课(SSO工程搭建)
- DOM
- ProgressBar使用步骤
- LeetCode 541. Reverse String II (字符串翻转)
- ISCC2017 pwn 200 —— 字符串格式化漏洞
- 算法练习笔记(十二)—— 超级洗衣机
- 给出几种排序总结
- 栅栏布局
- iOS脚本打包和持续集成
- 目标跟踪之ECO:Efficient Convolution Operators for Tracking
- 模板显式、隐式实例化和(偏)特化、具体化的详细分析
- 通讯录3.0(文件操作)