My Java Solution O(n)


  • 0
    W
    public String reverseStr(String s, int k) {
                int leng = s.length();
    	        int i = 0;
    	        int j = 0;
                StringBuffer sb = new StringBuffer();
    	        if(s.length() == 0) return s;
    	        if(k > s.length()) return sb.append(s).reverse().toString();
    	        while(i<leng){
    	            if(j%2 == 0){
    	            StringBuffer tmp = new StringBuffer();
    	            String sd = null;
    	            if((i+k)>=leng){
    	            	sd = tmp.append(s.substring(i,leng)).reverse().toString();
    	            }else {
    	            	 sd = tmp.append(s.substring(i,i+k)).reverse().toString();
    	            }
    	            sb.append(sd);
    	            i = i+k;
    	            j++;
    	            }else {
    	                if((i+k)>=leng){
    	                    sb.append(s.substring(i,leng));
    	                    i = i+k;
    	                }else{
    	                    sb.append(s.substring(i,i+k));
    	                    i = i+k;
    	                    j++;
    	                }
    	                
    	            }
    	        }
    	        return sb.toString();
        }
    

Log in to reply
 

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