Java StringBuilder solution, concise and easy to understand


  • 0
    S
    public class Solution {
        public String reverseStr(String s, int k) {
            StringBuilder sb = new StringBuilder();
            char[] tokens = s.toCharArray();
            int n = tokens.length;
            int idx = 0;
            while (idx < n) {
                int i = Math.min(n - 1, idx + k - 1);
                while (i >= idx) sb.append(tokens[i--]);
                i = idx + k;
                while (i < Math.min(idx + 2 * k, n)) sb.append(tokens[i++]);
                idx += 2 * k;
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

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