Easy To Understand.


  • 0
    E
    public class Solution {
        public String reverseStr(String s, int k) {
            if(s==null || s.length()<=1){
                return s;
            }
            StringBuilder sb = new StringBuilder(s);
            int len = s.length();
            int factor = 0;
            int left = k*factor;
            int right = k*(factor+1)-1;
            while(left<len){
                if(factor%2==0){
                    //reverse
                    right=right<len?right:len-1;
                    while(left<right){
                        char temp = sb.charAt(left);
                        sb.setCharAt(left, sb.charAt(right));
                        sb.setCharAt(right, temp);
                        left++;
                        right--;
                    }
                }
                factor++;
                left = k*factor;
                right = k*(factor+1)-1;
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.