My Java Solution [two pointer]


  • 1
    public class Solution {
        public String reverseStr(String s, int k) {
            // guard
            if (s == null || s.length() == 0) return s;
            
            char[] cArr = s.toCharArray();
            int ptr = 0;
    
            while(ptr < s.length()) {
                reverseHelper(cArr, ptr, k);
                ptr += 2*k;
            }
            
            return String.valueOf(cArr);
        }
        
        
        private void reverseHelper(char[] cArr, int start, int len) {
            int end = Math.min(start + len - 1, cArr.length-1);
        
            while (start < end) {
                char tmp = cArr[start];
                cArr[start] = cArr[end];
                cArr[end] = tmp;
                start++;
                end--;
            }
        }
    }
    

Log in to reply
 

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