Easy Java Solution using stack


  • 0
    D
    public class Solution {
        public String reverseStr(String s, int k) {
            
            
            //Base case: if string is null or j is 0, return string
            if(s==null || k==0)
                return s;
            
            //General case: if string is non empty and k is greater than 0
            //variable to store answer
            StringBuilder answer=new StringBuilder();
            
            //stack to store characters to be reversed
            Stack<Character> stack=new Stack<Character>();
            
            //for loop to iterate through the string
            for(int i=0;i<s.length();i++)
            {
                
                int res = i/k;
                
                //Case 1: if char is part of first k chars it has to be reversed, push down stack
                if((res % 2)==0)
                {
                    stack.push(s.charAt(i));
                }
                //Case 2: if char is between k to 2k chars, before appending, append chars in stack first
                else
                {
                    while(!stack.isEmpty())
                    {
                        answer.append(stack.pop());
                    }
                    
                    answer.append(s.charAt(i));
                }
            }
            
            //if characters present in the stack, append them to answer
            while(!stack.isEmpty())
            {
            	answer.append(stack.pop());
            }
            
            return answer.toString();
        }
    }
    

Log in to reply
 

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