Regular Java Solution with Random 6 Long Char


  • 0
    W

    //Use array to generate random number, it definitely reduces the reputation. //Also it checks the new tiny url exist in the map or not until it is a new one.
    // source code
    public class Codec {
    HashMap<String, String> long2tinyMap = new HashMap<>();
    HashMap<String, String> tiny2longMap = new HashMap<>();
    String base = "http://tinyurl.com/";
    String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";//62

    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        String tiny = getTiny();
        //generate the permutation.
        while(tiny2longMap.containsKey(tiny)) {
            tiny = getTiny();
        }
    
        long2tinyMap.put(longUrl, tiny);
        tiny2longMap.put(tiny, longUrl);
        return tiny;
    }
    
    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
        String longurl = tiny2longMap.get(shortUrl);
        return longurl;
    }
    
    private String getTiny() {
        Random random = new Random();
        char[] tinyArray = new char[6];
        for(int i = 0; i < 6; i++) {
            tinyArray[i] = str.charAt(random.nextInt(26));
        }
        return new String(tinyArray);
    }
    

    }


Log in to reply
 

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