码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] Reverse String II

时间:2018-07-16 13:59:11      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:lis   int   esc   eve   时间   origin   --   翻转   style   

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:
  1. The string consists of lower English letters only.
  2. 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

标签:lis   int   esc   eve   时间   origin   --   翻转   style   

原文地址:https://www.cnblogs.com/boris1221/p/9316974.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!