My ac solution


  • 0
    M
    public String reverseStr(String s, int k) {
    	    int i = 0;
    	    StringBuffer sb = new StringBuffer(s);
    	    while(i + 2*k <= s.length()){
    	        doRevert(sb, i, i + k - 1);
    	        i = i + 2 * k;
    	    }     
    	    doRevert(sb, i, Math.min(i + k - 1, s.length() - 1));
    	    return sb.toString();
    	}
    
    	private void doRevert(StringBuffer sb, int start, int end){
    	    while(start < end){
    	        char c = sb.charAt(start);
    	        sb.setCharAt(start, sb.charAt(end));
    	        sb.setCharAt(end, c);
    	        start++;
    	        end--;
    	    }
    	}

Log in to reply
 

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