反轉部分字符串 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

相關文章
相關標籤/搜索