BiruLyu
6/28/2017 - 9:54 PM

535. Encode and Decode TinyURL(ArrayList).java

public class Codec {
    private HashMap<String, String> code2url = new HashMap<String, String>();
    //private HashMap<String, String> url2code = new HashMap<String, String>();
    private String candidates = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private Random rand = new Random();
    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        String code = "";
        do {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 6; i++) {
                sb.append(candidates.charAt(rand.nextInt(62)));
            }
            code = sb.toString();
        }while(code2url.containsKey(code));
        
        code2url.put(code, longUrl);
        //url2code.put(longUrl,code);
        return code;
    }

    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
        return code2url.get(shortUrl);
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));
public class Codec {
    private ArrayList<String> urls = new ArrayList<String>();
    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        urls.add(longUrl);
        return String.valueOf(urls.size() - 1);
    }

    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
        int idx = Integer.valueOf(shortUrl);
        return idx > urls.size() ? "" : urls.get(idx);
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));