Java Lengthy but self-explanatory code ( 80ms)


  • 0
    H
    public String licenseKeyFormatting(String S, int K) {
            char[] stream= S.toCharArray();
            StringBuilder sb= new StringBuilder();
            int chars=0;
            for(char c:stream)
                if(c!='-') chars++;
            int dashes=chars/K;
             if(chars%K ==0) dashes--;
            int offset=0;
            int j=stream.length-1;
            while(j>=0){
            	if(stream[j]=='-')
            		{
            			j--; continue;
            		}
            	sb.append(Character.toUpperCase(stream[j--]));
            	offset++;
            	if(offset%K==0 && dashes>0)
            		{
            			sb.append('-');
            			dashes--;
            			offset=0;
            		}
            }
            
            return sb.reverse().toString();
            
        }
    

Log in to reply
 

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