[leetcode] Reverse String II
Posted Lin.B
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode] Reverse String II相关的知识,希望对你有一定的参考价值。
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]
分析:题目比较简单,翻译一下:对一个字符串s,要求每2k个字符中,前k个字符翻转。注意这里如果最后不满足k个字符,那么就翻转全部的剩下字符。
思路还是很简单的,要调用一个函数来完成翻转的功能。具体代码如下:
1 class Solution { 2 public String reverseStr(String s, int k) { 3 char[] array = s.toCharArray(); 4 for ( int i = 0 ; i < s.length() ; i += 2*k ){ 5 reverse(array,i,i+k-1); 6 } 7 return String.valueOf(array); 8 } 9 10 private void reverse(char[] array, int start, int end) { 11 if ( start > array.length ) return; 12 int low = start; 13 int high = Math.min(end,array.length-1); 14 while ( low < high ){ 15 char c = array[low]; 16 array[low] = array[high]; 17 array[high] = c; 18 low++; 19 high--; 20 } 21 } 22 }
运行时间3ms,击败100%的提交。
这里可以总结一下字符串翻转的小技巧,就是用两个指针来完成。
以上是关于[leetcode] Reverse String II的主要内容,如果未能解决你的问题,请参考以下文章