[Java]Divide and Conquer (10ms)


  • 0
    O

    Divide and Conquer (Recursive) :

    public class Solution {
         public String reverseStr(String s, int k) {
            int len = s.length();
            if (len < 2 * k) return len >= k ? reverse(s, k) : reverse(s, s.length());
            return reverse(s.substring(0, 2 * k), k) + reverseStr(s.substring(2 * k, len), k);
        }
    
        public String reverse(String s, int len) {
            int lo = 0, hi = len - 1;
            char[] chars = s.toCharArray();
            while (lo < hi) {
                chars[lo] ^= chars[hi];
                chars[hi] ^= chars[lo];
                chars[lo++] ^= chars[hi--];
            }
            return new String(chars);
        }
    }
    

    if wrong plz tell me ^_^


Log in to reply
 

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