Java O(n) 6ms(2017-06-29 15:25:45) solution


  • 0

    Not that it's better, it does practically the same speed as most solutions posted in the discussion. Just sharing a slightly different perspective.

    
    public class Solution {
        public String reverseStr(String s, int k) {
            if (s.length() == 0 || k == 0) return s;
            char[] chars = s.toCharArray();
            int n = chars.length;
            int m = n % (2 * k) != 0 ? n / (2 * k) + 1 : n / (2 * k);
            for (int i = 0; i < m; i++) {
                int hd, tl;
                if (i == m - 1 && (n - 2 * k * (m - 1)) < k) {
                    hd = i * 2 * k + 0;
                    tl = n - 1;
                } else {
                    hd = 0 + i * 2 * k;
                    tl = k - 1 + i * 2 * k;
                }
                while (hd < tl) {
                    char tmp = chars[tl];
                    chars[tl--] = chars[hd];
                    chars[hd++] = tmp;
                }
            }
            return String.valueOf(chars);
        }
    }
    

Log in to reply
 

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