Java Straightforward Method


  • 0
    Z
    public class Solution {
        public String reverseStr(String s, int k) {
            if (s==null || s.length()<2) return s;
            int len = s.length();
            char[] arr = s.toCharArray();
            int curr = 0, next = Math.min(k-1, len-1);
            while (curr < len-1) {
                int i = curr, j = next;
                while (i < j) {
                    char tmp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = tmp;
                    i++;
                    j--;
                }
                curr = next+1+k;
                next = Math.min(next+2*k, len-1);
            }
            return new String(arr);
        }
    }
    

Log in to reply
 

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