反转部分字符串 Reverse String II

问题:less

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.spa

Example:字符串

Input: s = "abcdefg", k = 2
Output: "bacdfeg"

Restrictions:string

  1. The string consists of lower English letters only.
  2. Length of the given string and k will in the range [1, 10000]

解决:io

【题目要求】每隔k隔字符,翻转k个字符,最后若是不够k个了的话,剩几个就翻转几个class

① 直接的方法就是先用n/k算出来原字符串s能分红几个长度为k的字符串,而后开始遍历这些字符串,遇到2的倍数就翻转,翻转的时候注意考虑下是否已经到s末尾了遍历

public class Solution {//10ms
    public String reverseStr(String s, int k) {
        char[] schar = s.toCharArray();
        int count = s.length() / k;//字符串能够被分为多少段
        for (int i = 0;i <= count ;i ++ ) {
            if(i % 2 == 0){
                if(i * k + k < s.length()){//确保有k个值
                    reverse(schar,i * k,i * k + k - 1);
                }else{//最后不够k个数
                    reverse(schar,i * k,s.length() - 1);
                }
            }
        }
        return new String(schar);
    }
    public void reverse(char[] schar,int start,int end){
        while(start <= end){
            char tmp = schar[start];
            schar[start] = schar[end];
            schar[end] = tmp;
            start ++;
            end --;
        }
    }
}方法

② 这种方法更好理解 一点。while

public class Solution {//7ms
    public String reverseStr(String s, int k) {
        int len = s.length();
        char schar[] = s.toCharArray();
        int i = 0;
        while (i < len){
            int j = Math.min(i+k-1,len-1);
            reverse(schar,i,j);
            i += 2 * k
        }
        return String.valueOf(schar);
    }
    public void reverse(char[] schar,int start,int end){
        while(start <= end){
            char tmp = schar[start];
            schar[start] = schar[end];
            schar[end] = tmp;
            start ++;
            end --;
        }
    }
}co

相关文章
相关标签/搜索