Very easy to understand Java solution O (n) 9ms


  • 0
    Q
      public String reverseStr(String s, int k) {
    		char[] chars = s.toCharArray();
    		int index = 0;
    		while(index<chars.length){
    			reverse(chars,index,k);
    			index += 2*k;
    		}
    		return new String(chars);
    
    	}
    
    	private void reverse(char[] chars, int i, int k) {
    		int begin = i;
    		int end = Math.min(chars.length-1,i+k-1);
    		while(begin<end){
    			char temp = chars[begin];
    			chars[begin] = chars[end];
    			chars[end] = temp;
    			begin++;
    			end--;
    		}
    	}
    

Log in to reply
 

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