Java 7ms AC solution, a little change from Reverse String I


  • 0
    B
        public String reverseStr(String s, int k) {
            if (s == null || k<=1) return s;
            char[] words = s.toCharArray();
            int len = words.length, index = 1, start=0, end=k-1;
            if (start < len && end >= len) end = len-1; // if s.length < k
            while (end < len) {
                while (start < end) {
                    words[start] = (char) (words[start] ^ words[end]);
                    words[end] = (char) (words[start] ^ words[end]);
                    words[start] = (char) (words[start++] ^ words[end--]);
                }
                index += 2;
                start = (index-1) * k;
                end = index * k -1;
                if (start < len && end >= len) end = len-1;
            }
            return String.valueOf(words);
        }
    

Log in to reply
 

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