Clean Java Solution, Loop and in-place swap, at every odd K only


  • 0
    A
    // Naive O(n)
    public String reverseStr(String s, int k) {
        char[] chArr = s.toCharArray();
        
        for (int i = 0; i < chArr.length; i += 2*k) {
            for (int a = i, b = Math.min(i+k-1, chArr.length-1); a < b; a++, b--) {
                if (chArr[a] == chArr[b]) continue;
                char swap = chArr[a];
                chArr[a] = chArr[b];
                chArr[b] = swap;
            }
        }
        return new String(chArr);
    }

Log in to reply
 

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