Easy One pass Java Solution


  • 0
    S
    public class Solution {
        public String reverseStr(String s, int k) {
            char[] c=s.toCharArray();
            int start=0;
            while(start<c.length){
                reverseChars(c, start,Math.min(start+k-1, c.length - 1)); // remaining characters might be less than k
                start = start+k+k; // skipping next k characters
            }
            return String.valueOf(c);
        }
        
        private void reverseChars(char[] c, int start, int end){
            while(start<end){
                char temp = c[start];
                c[start++] = c[end];
                c[end--] = temp;
            }
        }
    }
    

Log in to reply
 

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