Java solution very easy to understand


  • 0
    W
    class Solution {
        public String reverseStr(String s, int k) {
            StringBuilder sb = new StringBuilder();
            int flag = 0;
            for (int i = 0; i < s.length(); i += k) {
                if (flag % 2 == 0) {
                    for (int j = (i+k-1 <= s.length()-1 ? i+k-1 : s.length()-1); j >= i; j--) sb.append(s.charAt(j));
                } else {
                    for (int j = i; j <= (i+k-1 <= s.length()-1 ? i+k-1 : s.length()-1); j++) sb.append(s.charAt(j));
                }
                flag ^= 1;
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

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