Java Solution Using StringBuilder


  • 0
    L
       public String reverseStr(String s, int k) {
            StringBuilder result = new StringBuilder();
            int i = 0;
            while (i < s.length()) {
                
                if ((i+2*k) >= s.length()) {
                    if((i+k) > s.length()) {
                        result.append(reverse(s.substring(i, s.length())));
                        i = s.length();
                    }else {
                         result.append(reverse(s.substring(i, i+k)));
                         result.append(s.substring(i+k, s.length()));
                         i = s.length();
                        }
                }else{
                    result.append(reverse(s.substring(i, k+i)));
                    
                    result.append(s.substring(i+k, i+2*k));
                    i = i+2*k;
                }
            }
            return result.toString();
        }
        private String reverse(String s) {    	
        	String reverse = new StringBuffer(s).reverse().toString();  	
            return reverse;
        }
       
    }
    

Log in to reply
 

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