Java Solution


  • 0
    S
    public String reverseStr(String s, int k) {
        if(s==null||k==1) return s;
        
        char[] chars = s.toCharArray();
        int left=0, len=s.length();
    
        while(left+2*k<=len){ //reverse every 2k
            reverse(chars, left, left+k-1);
            left += 2*k;
        }
        
        if(left+k<=len){ //reverse first k
            reverse(chars, left, left+k-1);
        }else{ //reverse all remaining
            reverse(chars, left, len-1);
        }
        
        return String.valueOf(chars);
    }
    
    private void reverse(char[] chars, int start, int end){
        while(start<end){
            char tmp = chars[start];
            chars[start++] = chars[end];
            chars[end--] = tmp;
        }
    }

Log in to reply
 

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