Easy JAVA implementation with explanation

  • 0

    Please find the explanation in the code

    public class Solution {
        public String reverseStr(String s, int k) {
            StringBuilder sb = new StringBuilder();
            boolean flag = true; // Helps to determine whether to reverse or not in the current iteration
            for(int i=0;i<s.length();i+=k)
                StringBuilder sb2 = new StringBuilder(); // For extracting k characters
                if(i+k<=s.length()-1) //This check ensures you do not go out of bounds when using substring
                     sb2 = new StringBuilder(s.substring(i,i+k));
                     sb2 = new StringBuilder(s.substring(i));
                if(flag) // The flag is true, it means you need to reverse
                        sb.append(sb2.reverse()); // append the extracted substing in sb2 as reverse
                        flag = false; //Reset Flag for next iteration
                else // If flag is false, you need not reverse
                        sb.append(sb2); // append the extracted substring in sb2 as it is
                        flag = true; 
            return sb.toString();// Convert StringBuilder to String as return type is String

Log in to reply

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