[LeetCode] Reverse String II 翻转字符串之二
LeetCode string 字符串 II 之二 翻转 reverse
2023-09-11 14:21:37 时间
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 = 2 Output: "bacdfeg"
Restrictions:
- The string consists of lower English letters only.
- Length of the given string and k will in the range [1, 10000]
这道题是之前那道题Reverse String的拓展,同样是翻转字符串,但是这里是每隔k隔字符,翻转k个字符,最后如果不够k个了的话,剩几个就翻转几个。比较直接的方法就是先用n/k算出来原字符串s能分成几个长度为k的字符串,然后开始遍历这些字符串,遇到2的倍数就翻转,翻转的时候注意考虑下是否已经到s末尾了,参见代码如下:
解法一:
class Solution { public: string reverseStr(string s, int k) { int n = s.size(), cnt = n / k; for (int i = 0; i <= cnt; ++i) { if (i % 2 == 0) { if (i * k + k < n) { reverse(s.begin() + i * k, s.begin() + i * k + k); } else { reverse(s.begin() + i * k, s.end()); } } } return s; } };
在论坛里又发现了写法更为简洁的方法,就是每2k个字符来遍历原字符串s,然后进行翻转,翻转的结尾位置是取i+k和末尾位置之间的较小值,感觉很叼,参见代码如下:
解法二:
class Solution { public: string reverseStr(string s, int k) { for (int i = 0; i < s.size(); i += 2 * k) { reverse(s.begin() + i, min(s.begin() + i + k, s.end())); } return s; } };
类似题目:
参考资料:
https://discuss.leetcode.com/topic/82652/one-line-c/2
https://discuss.leetcode.com/topic/82626/java-concise-solution
相关文章
- Java实现 LeetCode 816 模糊坐标(暴力)
- Java实现 LeetCode 1162 地图分析(可以暴力或者动态规划的BFS)
- Java实现 LeetCode 503 下一个更大元素 II
- SQL Server实现 LeetCode 176 第二高的薪水
- Java实现 LeetCode 151 翻转字符串里的单词
- LeetCode(122):卖股票的最佳时机 II
- LeetCode-386. 字典序排数【深度优先遍历,递归】
- Atitit 命令行dsl传递参数的几种模式对比 cli url模式 键值对NameValuePair urlutil String string = " -host 101.13
- LeetCode - 593 有效的正方形
- LeetCode - 402 移掉 K 位数字
- TypeScript里string和String,真不是仅仅是大小写的区别
- Leetcode 2293. 极大极小游戏(可以.一次过)
- Leetcode:Swap Nodes in Pairs 单链表相邻两节点逆置
- 【LeetCode】Copy List with Random Pointer
- leetcode 345. Reverse Vowels of a String
- leetcode 387. First Unique Character in a String
- 【Leetcode刷题Python】234.回文链表
- 【LeetCode】 134.加油站