541. Reverse String II
来源:互联网 发布:archlinux vim python 编辑:程序博客网 时间:2024/04/30 10: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]
此题解答主要在于将循环判断条件分清,下面代码分三种情况:
当字符串长度大于2k时,进行前k个字符反转后将指针后移2k;
当字符串长度小于2k大于k时,进行前k个字符反转,结束循环;
当字符串长度小于k时,将剩余字符反转,结束循环;
代码如下:
class Solution {public:void reverse(string& s,int i, int k){char temp;for(int j = 0; j <= (k-i)/2;j++){temp = s[i+j];s[i+j] = s[k-j];s[k-j] = temp;}} string reverseStr(string s, int k) { int length = s.length() - 1; int i = 0; while(i<length){ if(i+k-1 <= length && i+2*k-1 >= length){ Solution::reverse(s, i, i+k-1); return s;} else if(i+k-1 >= length && i < length){Solution::reverse(s, i, length);return s;} else if(i+k-1 < length && i + 2*k-1 < length){Solution::reverse(s, i, i+k-1);i = i + 2*k;}}return s; }};
0 0
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- String:541. Reverse String II
- leetcode 541. Reverse String II
- Leetcode-541. Reverse String II
- java 关键字static
- 【GDSOI2017第三轮模拟】Travel Plan(DP)
- leetcode120
- Split()拆分字符串与StringTokenizer拆分字符串
- 软件包管理
- 541. Reverse String II
- C#模拟鼠标在指定区域进行指定操作的小工具
- 程序员日常工作英文20170422
- ST算法解RMQ问题
- java基础总结19-java常用API(StringBuffer和Arrays工具类)
- 二分图的最大匹配——最大流EK算法
- IIC代码
- unity bug
- Get started with Docker 中文文档(2)——Part 2: Containers