Verbose Java Solution, StringBuilder(s)


  • 4

    Tried to maximize usage of StringBuilder :)

    public class Solution {
        public String reverseStr(String s, int k) {
            StringBuilder sb = new StringBuilder();
            
            int i = 0, j = 0;
            while (i < s.length()) {
                // first k
                j = i + k <= s.length() ? i + k : s.length();
                sb.append((new StringBuilder(s.substring(i, j))).reverse().toString());
                
                if (j >= s.length()) break;
                
                // second k
                i = j;
                j = i + k <= s.length() ? i + k : s.length();
                sb.append(s.substring(i, j));
                
                i = j;
            }
            
            return sb.toString();
        }
        
    }
    

  • 0
    T

    The code is clean and clear. Very clever to use the reverse() method of StringBuilder.

    I implemented the reverse by hand, code is as following:

    public String reverseStr(String s, int k) {
    		char[] s1 = s.toCharArray();
    		int i = 0, j = 2 * k - 1;
    		for (; j < s1.length; i += 2 * k, j += 2 * k) {
    			int m = i;
    			int n = j - k;
    			while (m < n) {
    				char temp = s1[m];
    				s1[m] = s1[n];
    				s1[n] = temp;
    				m++;
    				n--;
    			}
    		}
    		if ((s1.length - i < 2 * k) && (s1.length - 1 - i >= k)) {
    			int m = i;
    			int n = i + k - 1;
    			while (m < n) {
    				char temp = s1[m];
    				s1[m] = s1[n];
    				s1[n] = temp;
    				m++;
    				n--;
    			}
    		} else if (s1.length - 1 - i < k) {
    			int m = i;
    			int n = s1.length - 1;
    			while (m < n) {
    				char temp = s1[m];
    				s1[m] = s1[n];
    				s1[n] = temp;
    				m++;
    				n--;
    			}
    		}
    		return new String(s1);

  • 1

    Initialize new stringbuilder will obviously increase your program's cost


Log in to reply
 

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