Easy Java Solution using a boolean variable


  • 0
    F

    I found using a boolean variable less error-prone than by dealing with pointer positions.

    class Solution {
        public String reverseStr(String s, int k) {
            char[] chars = s.toCharArray();
            boolean toreverse = true;
            for (int i = 0; i < s.length(); i+=k) {
                if (toreverse) {
                    reverse(chars, i, Math.min(i+k-1, chars.length-1));
                }
                toreverse = !toreverse;
            }
            return new String(chars);
        }
        
        private void swap(char[] chars, int i, int j) {
            char tmp = chars[i];
            chars[i] = chars[j];
            chars[j] = tmp;
        }
        
        private void reverse(char[] chars, int lo, int hi) {
            while (lo < hi) {
                swap(chars, lo++, hi--);
            }
        }
    }
    

Log in to reply
 

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