lintcode/leetcode由易至难第21题:Encode and Decode TinyURL

来源:互联网 发布:seo团队 编辑:程序博客网 时间:2024/06/06 02:08

Problem:

Note: This is a companion problem to the System Design problem: Design TinyURL.

TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.

Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.

Code:

public class Codec {    List<String> s = new ArrayList<String>();    // Encodes a URL to a shortened URL.    public String encode(String longUrl) {        if(longUrl == null) return "null";        s.add(longUrl); //熟悉list的add();        return String.valueOf(s.size()-1);  //熟悉valueOf;    }    // Decodes a shortened URL to its original URL.    public String decode(String shortUrl) {                int index = Integer.valueOf(shortUrl);        if(index >= s.size()) return "null";        return s.get(index); //熟悉list的get();    }}// Your Codec object will be instantiated and called as such:// Codec codec = new Codec();// codec.decode(codec.encode(url));


Code2:

public class Codec {    Map<Integer,String> map = new HashMap<Integer,String>();  //用hashmap来建立对应关系    int index = 0;    // Encodes a URL to a shortened URL.    public String encode(String longUrl) {        map.put(index,longUrl);        return String.valueOf(index++);    }    // Decodes a shortened URL to its original URL.    public String decode(String shortUrl) {        return map.get(Integer.valueOf(shortUrl));    }}// Your Codec object will be instantiated and called as such:// Codec codec = new Codec();// codec.decode(codec.encode(url));


Code3:

public class Codec {    Map<Integer,String> map = new HashMap<Integer,String>();    // Encodes a URL to a shortened URL.    public String encode(String longUrl) {        map.put(longUrl.hashCode(),longUrl);  //用hashcode来建立对应关系;        return String.valueOf(longUrl.hashCode());    }    // Decodes a shortened URL to its original URL.    public String decode(String shortUrl) {        return map.get(Integer.valueOf(shortUrl));    }}// Your Codec object will be instantiated and called as such:// Codec codec = new Codec();




原创粉丝点击