My Java Solution


  • 0
    V

    If the number is not already in the string, try appending a piece of it in front or back

    public String crackSafe(int n, int k) {
    		StringBuilder sb = new StringBuilder(String.format("%0" + n +"d", 0));
    		for (int i = 1; i < Math.pow(k, n); i++) {
    			String num = Integer.toString(i, k);
    			String iToStr = String.format("%" + n +"s", num).replace(' ', '0');
    			
    			if (sb.toString().matches(".*" + iToStr + ".*")) 
    				continue;
    			
    			boolean done = false;
    			for (int j = n - 1; j > 0; j--) {
    				if (sb.substring(0, j).equals(iToStr.substring(n - j))) {
    					sb.insert(0, iToStr.substring(0, n - j));
    					done = true;
    					break;
    				} else if (sb.substring(sb.length() - j).equals(iToStr.substring(0, j))) {
    					sb.append(iToStr.substring(j));
    					done = true;
    					break;
    				}
    			}
    			if (!done)
    				sb.append(iToStr);
    		}
            return sb.toString();
        }
    

Log in to reply
 

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