535. Encode and Decode TinyURL #
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.
Problem Summary #
TinyURL is a URL shortening service. For example: when you enter a URL https://leetcode.com/problems/design-tinyurl, it returns a shortened URL http://tinyurl.com/4e9iAk.
Requirement: Design the TinyURL encryption encode and decryption decode methods. There is no restriction on how your encryption and decryption algorithms are designed and work. You only need to ensure that a URL can be encrypted into a TinyURL, and that this TinyURL can be restored to the original URL using the decryption method.
Solution Approach #
- Easy problem. Since the problem does not specify the
encode()algorithm, there is a lot of freedom. The simplest approach is to store the originalURLand record its index position in a string array. Duringdecode(), restore the originalURLaccording to the stored index.
Code #
package leetcode
import (
"fmt"
"strconv"
"strings"
)
type Codec struct {
urls []string
}
func Constructor() Codec {
return Codec{[]string{}}
}
// Encodes a URL to a shortened URL.
func (this *Codec) encode(longUrl string) string {
this.urls = append(this.urls, longUrl)
return "http://tinyurl.com/" + fmt.Sprintf("%v", len(this.urls)-1)
}
// Decodes a shortened URL to its original URL.
func (this *Codec) decode(shortUrl string) string {
tmp := strings.Split(shortUrl, "/")
i, _ := strconv.Atoi(tmp[len(tmp)-1])
return this.urls[i]
}
/**
* Your Codec object will be instantiated and called as such:
* obj := Constructor();
* url := obj.encode(longUrl);
* ans := obj.decode(url);
*/