文章目录
  1. 1. 文档更新说明
  2. 2. 前言
  3. 3. 535. Encode and Decode TinyURL
    1. 3.1. Example1
    2. 3.2. Note
    3. 3.3. Infer
    4. 3.4. Solution

文档更新说明

  • 最后更新 无
  • 首次更新 2017年05月18日

前言

  使用Swift语言完成LetCode题目,难度Medium,就不多介绍了.

535. Encode and Decode 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.

Subscribe to see which companies asked this question.

Example1

Note

Infer

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
////
//// main.swift
//// TestSwiftCommandLine
////
//// Created by Cocos on 2016/10/27.
//// Copyright © 2016年 Cocos. All rights reserved.
////
class Solution {
let dictStr = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
var seq = 0
var urlMapL2S: [String: String] = [:]
var urlMapS2L: [String: String] = [:]
//短地址长度
let shortLength = 6
//原理就是对longUrl进行映射
func encode(_ longUrl: String) -> String {
if let s = urlMapL2S[longUrl] {
return s
}
var res = ""
var count = seq
seq += 1
while count != 0 {
res += String(dictStr[dictStr.index(dictStr.startIndex, offsetBy: count % dictStr.characters.count)])
count /= dictStr.characters.count
}
for _ in res.characters.count ..< shortLength {
res = "0" + res
}
urlMapL2S[longUrl] = res
urlMapS2L[res] = longUrl
return res
}
func decode(_ shortUrl: String) -> String {
return urlMapS2L[shortUrl]!
}
}
文章目录
  1. 1. 文档更新说明
  2. 2. 前言
  3. 3. 535. Encode and Decode TinyURL
    1. 3.1. Example1
    2. 3.2. Note
    3. 3.3. Infer
    4. 3.4. Solution