Concise Java solution Using array


  • 0
    C
        public String reverseStr(String s, int k) {
            if(s == null || s.length() == 0) return "";
            int i = 0;
            char[] list = s.toCharArray();
            while(i * k < s.length()) {
                swap(list, i * k, Math.min( (i + 1) * k - 1, s.length() - 1));
                i += 2;
            }
            return new String(list);
        }
    
        private void swap(char[] list, int s, int e) {
            while(s < e) {
                char tmp = list[s];
                list[s++] = list[e];
                list[e--] = tmp;
            }
        }
    

Log in to reply
 

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