Java O(n) solution


  • 0
    M
    public class Solution {
        
        public static String reverseStr(String s, int k) {
    
            if (s == null || s.length() == 1) return s;
    
            if (s.length() < k) return new String(reverseRange(s.toCharArray(), 0, s.length() -1));
    
            char[] orig = s.toCharArray();
            char[] result = new char[s.length()];
    
            int pos = 0;
            boolean jump = false;
    
            while (pos < orig.length) {
                int start = pos;
                int end = (pos + k) - 1;
                if (end > orig.length -1) end = orig.length -1;
                if (!jump) {
                    char[] rev = reverseRange(orig, start, end);
                    for (int i = 0; i < rev.length; i++) {
                        result[pos++] = rev[i];
                    }
                    jump = true;
                } else {
                    for (int i = start; i <= end && i < orig.length; i++) {
                        result[pos++] = orig[i];
                    }
                    jump = false;
                }
            }
            return new String(result);
        }
    
        private static char[] reverseRange(char[] a, int start, int end) {
            char[] result = new char[(end - start) + 1];
            int pos = 0;
            for (int i = end; i >= start; i--) {
                result[pos++] = a[i];
            }
            return result;
        }
    
    }
    

Log in to reply
 

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