Java 10 ms solution , append in intervals


  • 0
    C
    public String reverseStr(String s, int k) {
            
            //O(n) - 10ms
            StringBuilder sb = new StringBuilder("");
            int len = s.length();
            int i = 0 ; 
            
            // len < 2k condition, reverse , append and return
            if(len < 2*k && len >= k) return sb.append(new StringBuilder(s.substring(0,k)).reverse() ).append(s.substring(k)).toString();
            
            while(i < len){
                
                //reverse
                if(i+k < len) sb.append( new StringBuilder(s.substring(i,i+k)).reverse() );
                else {
                    //end of string reverse and break
                    sb.append(  new StringBuilder(s.substring(i)).reverse() );
                    break;
                }
                i = i + k; //move i in k intervals
                
                //append the rest in interval
                if(i + k < len) sb.append( new StringBuilder(s.substring(i,i+k)) );
                else {
                    //end of string,append and break
                    sb.append(  new StringBuilder(s.substring(i)) );
                    break;
                }
                i = i + k; //move i in k intervals
            }
          
             return sb.toString(); // return string result
        }
    
    
    

Log in to reply
 

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