解法一

计数作为编码。

  1. public class Codec {
  2. private Map<Integer, String> map;
  3. private int index;
  4. public Codec() {
  5. map = new HashMap<>();
  6. index = 0;
  7. }
  8. // Encodes a URL to a shortened URL.
  9. public String encode(String longUrl) {
  10. map.put(index, longUrl);
  11. return "http://tinyurl.com/" + index++;
  12. }
  13. // Decodes a shortened URL to its original URL.
  14. public String decode(String shortUrl) {
  15. return map.get(Integer.parseInt(shortUrl.substring(19, shortUrl.length())));
  16. }
  17. }
  18. // Your Codec object will be instantiated and called as such:
  19. // Codec codec = new Codec();
  20. // codec.decode(codec.encode(url));