Java solution using StringBuilder


  • 0
    public String reverseStr(String s, int k) {
            StringBuilder res = new StringBuilder();
            int i = 0;
            while(i < s.length()){
                StringBuilder sb = new StringBuilder();
                while(i < s.length() && i % (2 * k) >= 0 && i % (2 * k) < k){
                    sb.append(s.charAt(i ++));
                }
                res.append(sb.reverse().toString());
                while(i < s.length() && i % (2 * k) >= k){
                    res.append(s.charAt(i ++));
                }
            }
            return res.toString();
        }
    

Log in to reply
 

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