TinyURL 문제 풀이 보고서 인 코딩 및 디 코딩 (Python & C + +)
목차
제목 설명
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.
문제 풀이 방법
방법 1: 배열
이 문 제 는 불 성 문제 다.아무런 요구 도 하지 않 고 인 코딩, 디 코딩 만 할 수 있 으 면 됩 니 다.큰 신의 생각 으로 배열 로 저장 한 다음 에 모든 사이트 가 있 는 배열 의 번 호 를 짧 은 사이트 주소 로 인 코딩 하고 디 코딩 합 니 다.
class Codec:
def __init__(self):
self.urls = []
def encode(self, longUrl):
"""Encodes a URL to a shortened URL.
:type longUrl: str
:rtype: str
"""
self.urls.append(longUrl)
return "http://tinyurl.com/" + str(len(self.urls) - 1)
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL.
:type shortUrl: str
:rtype: str
"""
return self.urls[int(shortUrl.split('/')[-1])]
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))
방법 2: 사전
이 치 는 같 지만 사실 사전 은 좀 더 간단 하 다.
class Codec:
def __init__(self):
self.count = 0
self.d = dict()
def encode(self, longUrl):
"""Encodes a URL to a shortened URL.
:type longUrl: str
:rtype: str
"""
self.count += 1
self.d[self.count] = longUrl
return str(self.count)
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL.
:type shortUrl: str
:rtype: str
"""
return self.d[int(shortUrl)]
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))
C + + 버 전의 코드 는 다음 과 같 습 니 다.
class Solution {
public:
// Encodes a URL to a shortened URL.
string encode(string longUrl) {
count++;
d[count] = longUrl;
return to_string(count);
}
// Decodes a shortened URL to its original URL.
string decode(string shortUrl) {
return d[stoi(shortUrl)];
}
private:
int count = 0;
map<int, string> d;
};
// Your Solution object will be instantiated and called as such:
// Solution solution;
// solution.decode(solution.encode(url));
날짜.
2018 년 2 월 5 일 2018 년 12 월 2 일 - 또 일요일
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
python 문자열 입력으로 모든 유효한 IP 주소 생성(LeetCode 93번 문제)이 문제의 공식 난이도는 Medium으로 좋아요 1296, 반대 505, 통과율 35.4%를 눌렀다.각 항목의 지표로 말하자면 보기에는 약간 규범에 맞는 것 같지만, 실제로도 확실히 그렇다.이 문제의 해법과 의도는 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.