(Easy) Reverse String - LeetCode

Description:

Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.

Example:

Input: s = "abcdefg", k = 2
Output: "bacdfeg"

Restrictions:

  1. The string consists of lower English letters only.
  2. Length of the given string and k will in the range [1, 10000]

Solution:

class Solution {
    public String reverseStr(String s, int k) {
    
    if (s ==null ||s.length() ==0){
        
        return "";
    }
        
    if(k ==0){
        
        return s;
    }
        
         
    int z =0;
        int tt= 0;
    if((s.length()% (2*k))!=0){
        tt = s.length()/(2*k)+1;
    }
        else{ tt= s.length()/ (2*k);} 
    String [] st = new String[tt];
        
        System.out.println(tt);
        
    for(int i = 0; i<=s.length()-2*k;i=i+2*k ){
         
          st[z++] = s.substring(i,i+2*k);
    
         
    }   
    
    int res = s.length() %(2*k) ;
    
   
   String result = "";
    for(int i = 0; i<st.length; i++){
        if(st[i]!=null)
        result = result + reverse(st[i].substring(0,k)) + st[i].substring(k,2*k);
    }
        
         String last =s.substring(z*2*k ,s.length() );
    
 
        if(res >0){
        
         if(res>=k&&res <2*k){
             
              result = result+ reverse(last.substring(0,k));
             
             String tmp ="";
             
             for(int i = k; i<last.length();i++){
                 
                 tmp = tmp+last.charAt(i);
             }
              
             result = result+tmp;
         }
            else{
              result = result +  reverse(last);
            }
         
    } 
    
        
        return result;
    }    
    
    public String reverse(String s){
        
         StringBuffer sb = new StringBuffer(s);
        
        return   sb.reverse().toString();
    }
}
    
    

猜你喜欢

转载自www.cnblogs.com/codingyangmao/p/11322258.html