LeetCode 541. Reverse String II (反转字符串 II)
2018-04-08 10:43
351 查看
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]
题目标签:String
今天登陆突然发现LeetCode 有中文版本了- -,再也不用纠结于 如何翻译题目名字了。 题目给了我们一个string s 和 int k,让我们每次在2k 个 chars 里只反转 k 个chars。 利用Reverse String 里的 two pointers 来反转k 个chars,每一次增加 i by 2*k 就可以了。 具体请看code。
Java Solution:
Runtime beats 67.31%
完成日期:04/07/2018
关键词:two pointers
关键点:swap left and right chars
class Solution { public String reverseStr(String s, int k) { char [] c_arr = s.toCharArray(); for(int i=0; i<c_arr.length; i=i+2*k) { int left = i; int right = Math.min(i + k - 1, c_arr.length - 1); while(left < right) { // swap char char temp = c_arr[left]; c_arr[left] = c_arr[right]; c_arr[right] = temp; left++; right--; } } return new String(c_arr); } }
参考资料:n/a
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/
相关文章推荐
- [LeetCode]541. Reverse String II(间隔反转字符串)
- leetcode 541. Reverse String II 反转字符串
- leetcode -- 541. Reverse String II 【字符串反转 + 双指针 + 状态记录 + 数组与堆内存】
- LeetCode 541. Reverse String II (字符串翻转)
- leetcode Reverse String II 反转字符串
- [leetcode, python] Reverse Words in a String 反转字符串
- LeetCode-541. Reverse String II (Java)
- leetcode541 Reverse StringII java
- [leetcode, python] Reverse Words in a String 反转字符串
- [leetcode, python] Reverse Words in a String 反转字符串
- [leetcode]541. Reverse String II
- Leetcode OJ Contest23 Reverse String II_Leetcode541
- [leetcode, python] Reverse Words in a String 反转字符串
- LeetCode 541. Reverse String II(C++版)
- leetcode Reverse Vowels of a String 反转字符串中的母音
- LeetCode 541 Reverse String II
- [leetcode, python] Reverse Words in a String 反转字符串
- LeetCode 541 Reverse String II
- LeetCode 541:Reverse String II (c++)
- LeetCode | Reverse Words in a String(字符串中的单词序反转)