Java Solution - simple Product and Remainder way


  • 0
    R
    public String reverseStr(String s, int k) {
            if(s==null || s.length()==0)
                return null;
            int len = s.length();
            if(k > len)    // Simply reverse the string
                return new String(((new StringBuilder(s)).reverse()));
    
            int units = len/k;   // units of 'k'
            int rem = len%k;
            char[] arr = s.toCharArray();
            int index = 0;
            for(int i = 1;i<= units;i=i+2){
                      int rightEnd = index+k-1;  // the point till you want to reverse, 'k' distance away from 'index'
                      int saveState = index+k-1;  // to move to next swap area
                      while(index < rightEnd){
                                 char temp = arr[index];
                                 arr[index] = arr[rightEnd];
                                  arr[rightEnd] = temp;
                    
                                 index++;
                                 rightEnd--;
                         }
                
                index = saveState+k+1;
            }
           if(rem!=0){                   // take care of the corner case, where <=k left, reverse them
                if(units%2==0){
                    int left = units*k; int right = left+rem-1;
                    while(left < right){
                        char temp = arr[left];
                        arr[left] = arr[right];
                        arr[right] = temp;
                        left++;
                        right--;
                    }
                }
            }
            
            
            return new String(arr);
        }

Log in to reply
 

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