Java 5 lines clean solution


  • 41
    Y
        public String licenseKeyFormatting(String s, int k) {
            StringBuilder sb = new StringBuilder();
            for (int i = s.length() - 1; i >= 0; i--)
                if (s.charAt(i) != '-')
                    sb.append(sb.length() % (k + 1) == k ? '-' : "").append(s.charAt(i));
            return sb.reverse().toString().toUpperCase();
        } 
    

  • 0
    Y

  • 10

    Found this little gem -
    https://discuss.leetcode.com/topic/75225/java-easy-to-understand-solution

     public String licenseKeyFormatting(String S, int K) {
        S = S.replaceAll("-", "").toUpperCase();
        StringBuilder sb = new StringBuilder(S);
        // Starting from the end of sb, and going backwards. 
        int i = sb.length() - K;
        while(i > 0) {
            sb.insert(i, '-');
            i = i - K;
        }
        return sb.toString();
    }

  • 4
    Y

    @zzhai insert(i, '-') might get slow since it is O(n)


  • 11

    @yuxiangmusic very sneaky using

    sb.length() % (k + 1) == k
    

    I didn't think of that, I just keep a count of actual characters used, a little simpler.

        public string LicenseKeyFormatting(string S, int K) 
        {
            StringBuilder sb = new StringBuilder();
            int charLen = 0;
            for (int i = S.Length - 1; i >= 0; i--)
            {
                if (S[i] != '-')
                {
                    if (charLen > 0 && charLen % K == 0)
                    {
                        sb.Append('-');
                    }
                    sb.Append(Char.ToUpper(S[i]));
                    charLen++;
                }
            }
            
            char[] chars = sb.ToString().ToCharArray();
            Array.Reverse(chars);
            return new string(chars);
        }
    

  • 1

    3 Lines

        public String licenseKeyFormatting(String str, int k) {
            StringBuilder sb = new StringBuilder(str.toUpperCase().replaceAll("-",""));
            for(int p = sb.length()-k; p>0; p-=k) sb.insert(p, "-");
            return sb.toString(); 
        }
    

  • 1

    Avoid appending a empty string:

        public String licenseKeyFormatting(String S, int K) {
          StringBuilder sb = new StringBuilder();
          char[] sc = S.toCharArray();
          for(int i = sc.length - 1; i >= 0; i--){
            if(sc[i] == '-') continue;
            if(sb.length() % (K + 1) == K) sb.append('-');
            sb.append(sc[i]);
          }
          return sb.reverse().toString().toUpperCase();
        }

  • 0
    P
    This post is deleted!

  • 0
    R

    @yuxiangmusic Neat solution. One suggestion:
    Instead of append(s.charAt(i)) you can call append(c >= 97 && c <= 122 ? (char) (c - 32) : c). That way you don't need to call toUppercase() and hence will save one iteration over the string.


  • 0
    A

    Aren't all of these StringBuilder solutions using O(n) space? What about an O(1) space, O(n) time solution?


  • 0

    @aswin4

    If directly use string concatenations, it'll be much slower than StringBuilder.


  • 0
    L
      public String licenseKeyFormatting(String S, int K) {
           StringBuffer ret = new StringBuffer();
    
            String s = S.replace("-", "");
            int idx = 0;
            for (int i = s.length() - 1; i >= 0; i--) {
                ret.append(String.valueOf(s.charAt(i)).toUpperCase());
                if (++idx % K == 0 && idx != s.length()) {
                   ret.append("-");
                }
            }
    
    
            return ret.reverse().toString();
        }
    

  • 0
    J

    @zzhai Awesome!


  • 0
    Y
    public class Solution {
        public String licenseKeyFormatting(String s, int k) {
            StringBuilder res = new StringBuilder();
            int cnt = 0;
            for(int i=s.length()-1;i>=0;i--){
                char cur = s.charAt(i);
                if(cur!='-'){
                    if(cnt%k==0 && cnt!=0) res.append('-');
                    res.append((cur>=97 && cur<=122)?(char)(cur-32):cur);//to uppercase
                    cnt++;
                }
            }
            return res.reverse().toString();
        }
    }
    

  • 0
    X

    I really like this one pass solution, it's way faster than my solution.


  • 0

    very clean code. thanks.


  • 0

    said in Java 5 lines clean solution:

    sb.append(sb.length() % (k + 1) == k ? '-' : "").append(s.charAt(i));
    This is great!

    but i'm having trouble with this part. can you help?


  • 0
    W

    Hi,I realize your thought into Python.But it didn't work.The reply is "Time Limited". Can you help me out?

    class Solution(object):
        def licenseKeyFormatting(self, S, K):
            size = len(S)
            S = S.upper()
            s1 = ""
            for i in range(size-1,-1,-1):
                if(S[i]!="-"):
                    if (len(s1)%(K+1)==K):
                        s1 = s1 + "-"
                    s1 = s1 + S[i]
            return s1[::-1]
    

Log in to reply
 

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