Article From:https://www.cnblogs.com/SkyeAngel/p/9060718.html

Reverse String II

 

Their own solution:

That is to use a StringBuffer to receive a string, using a pointer to indicate which part of the current K is, when I + K < s.length (), it is proved that the I can be reversed from the I to the I + k – 1 part.And from I + K part to I + 2 * k part is directly splicing, conditional J &lt, s.length () can be restricted, but forThe last small part of the restIf it is necessary to reverse, then you can not use the conditions used in the reverse above: from J = I + k – 1, but from j = s.length() – 1Start to the end of I

class Solution {
    public String reverseStr(String s, int k) {
        if(s == null || s.length() == 0 || k == 0) return s;
        StringBuffer str = new StringBuffer();
        int i = 0;
        while(i + k < s.length()){
            for(int j = i + k - 1; j >= i && j < s.length(); j--){
                str.append(s.charAt(j));
            }
            i += k;
            for(int j = i; j < i + k && j < s.length(); j++){
                str.append(s.charAt(j));
            }
            i += k;
        }
        
        if(i + k >= s.length()){
            for(int j = s.length() - 1; j >= i; j--){
                str.append(s.charAt(j));
            }
        }
        
        return str.toString();
    }
}

  

 

 public String reverseStr(String s, int k) {
        if(s == null || s.isEmpty()){return s;}
        StringBuilder sb = new StringBuilder();
        boolean reverse = true;
        for(int i = 0; i < s.length(); i = i + k, reverse = !reverse){
            int end = (i + k) < s.length() ? (i + k - 1) : s.length()-1;
            if(reverse)
                for(int j = end; j >= i; j--){sb.append(s.charAt(j));} // Copy in reverse
            else
                for(int j = i; j <= end; j++){sb.append(s.charAt(j));} // Copy as it is
        }
        return sb.toString();
    }

  

 

public String reverseStr(String s, int k) {
        char[] ch = s.toCharArray();
        for (int i = 0; i < ch.length; i += 2 * k) {
            rev(ch, i, i + k);
        }
        return String.valueOf(ch);
    }
    
    private void rev(char[] ch, int i, int j) {
        j = Math.min(ch.length, j) - 1;
        for (; i < j; i++, j--) {
            char tmp = ch[i];
            ch[i] = ch[j];
            ch[j] = tmp;
        }
    }

  

Leave a Reply

Your email address will not be published. Required fields are marked *