Concise Java - StringBuilder


  • 0

    1 pass. Conveniently using StringBuilder -
    If characters need to reverse, we can sb.insert(); if reversal isn't required, then simply sb.append().

        public String reverseStr(String s, int k) {
            StringBuilder sb = new StringBuilder(); 
            int fold = 0; 
            for (int i = 0; i < s.length(); i++) {
                fold = i / k; 
                if (fold % 2 == 0) sb.insert(fold * k, s.charAt(i));
                else sb.append(s.charAt(i));
            }
            return sb.toString(); 
        }

Log in to reply
 

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