API Methods

StringBuilder

insert at the beginning => O(n)

  • so instead of inserting at the beginning overtime, we can append the character and then reverse after append all
String
  • toUpperCase()

Mistakes

corner cases

  • "--a-a-a-a--" 2
public class Solution {
    public String licenseKeyFormatting(String S, int K) {
        StringBuilder result = new StringBuilder();
        int count = 0;
        for (int i = S.length() - 1; i >= 0; --i) {
            if (S.charAt(i) != '-') {
                if (count == K) {
                    result.append('-');
                    count = 0;
                }
                result.append(S.charAt(i));
                count++;
            }
        }

        return result.reverse().toString().toUpperCase();
    }
}

results matching ""

    No results matching ""