Java, StringBuilder, straightforward


  • 0
    D
    public class Solution {
        public String reverseStr(String s, int k) 
        {
            StringBuilder sb = new StringBuilder();
            
            int len = s.length();
            int i = 0;
            while (i < len)
            {
                int distToEnd = len - i;
                // less than k characters left
                if (distToEnd < k)
                {
                    // reverse all rest characters
                    sb.append(new StringBuilder(s.substring(i)).reverse());
                    break;
                }
                // less than 2k but greater than or equal to k characters
                else if (distToEnd >= k && distToEnd < 2 * k)
                {
                    sb.append(new StringBuilder(s.substring(i, i + k)).reverse()).append(s.substring(i + k));
                    break;
                }
                else
                {
                    sb.append(new StringBuilder(s.substring(i, i + k)).reverse()).append(s.substring(i + k, i + 2 * k));
                    i += 2*k;
                }
            }
            
            return sb.toString();
        }
    }
    

Log in to reply
 

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