Java O(N)


  • 0
    C
    public class Solution {
        public String reverseStr(String s, int k) {
            if (s == null || s.length() == 0 || k <= 0) {
                return  "";
            }
            char[] str = s.toCharArray();
            int start = 0, end = 0;
            while (start + 2 * k <= str.length) {
                reverse(str, start, start + k - 1);
                start += 2 * k;
            }
            reverse(str, start, Math.min(str.length - 1, start + k - 1));
            return new String(str);
        }
        
        private void reverse(char[] array, int i, int j) {
            while (i < j) {
                char tmp = array[i];
                array[i] = array[j];
                array[j] = tmp;
                ++i;
                --j;
            }
        }
    }
    

Log in to reply
 

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