Please help improve my approach


  • 0
    A

    Here is my solution to Reverse String II

    public class Solution {
        public String reverseStr(String s, int k) {
            if(s==null||s.length()<1||k>s.length())
                return s;
            if(2*k>s.length())
                return getReversal(0,k,s).toString();
                
            StringBuilder current = new StringBuilder(s);
            
            for(int i=0;i<s.length();)
            {
               
                if(i+2*k<s.length())
                {
                    current = getReversal(i,k,current.toString());
                   
                    i=i+2*k;
                }
                else
                {
                    current = getReversal(i,k,current.toString());
                    break;
                }
            }
            
            return current.toString();
        }
        
        StringBuilder getReversal(int startingIndex, int k, String input)
        {
            if(startingIndex==input.length()-1||startingIndex+k>input.length())
             return new StringBuilder(input);
             
            String alreadyDone = input.substring(0,startingIndex);
            String strToReverse = input.substring(startingIndex,startingIndex+k);
            String remaining = input.substring(startingIndex+k);
            
            StringBuilder reversal = new StringBuilder();
            
            for(String r : strToReverse.split(""))
            {
                reversal.append(r);
            }
            
            return new StringBuilder(alreadyDone+reversal.reverse().toString()+remaining);
        }
    }
    

    I know i'm very close but i keep failing on edge cases like

    abcdefg
    8
    

    i cant figure out what i need to do to sinish this


Log in to reply
 

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