首页 > 其他 > 详细

LeetCode Reverse String II

时间:2017-04-01 09:48:24      阅读:235      评论:0      收藏:0      [点我收藏+]

原题链接在这里:https://leetcode.com/problems/reverse-string-ii/#/description

题目:

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] 

题解:

Reverse String的进阶题目.

每2k个char中前k个char swap.

Time Complexity: O(n), n = s.length(). Space: O(n).

AC Java:

 1 public class Solution {
 2     public String reverseStr(String s, int k) {
 3         int len = s.length();
 4         char [] charArr = s.toCharArray();
 5         int i = 0;
 6         while(i < len){
 7             int j = Math.min(i+k-1, len-1);
 8             swap(charArr, i, j);
 9             i += 2*k;
10         }
11         
12         return new String(charArr);
13     }
14     
15     private void swap(char [] s, int i, int j){
16         while(i<j){
17             char temp = s[i];
18             s[i] = s[j];
19             s[j] = temp;
20             i++;
21             j--;
22         }
23     }
24 }

 

LeetCode Reverse String II

原文:http://www.cnblogs.com/Dylan-Java-NYC/p/6654368.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!