分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

Leetcode 535: Encode and Decode TinyURL

发布时间:2023-09-06 01:33责任编辑:熊小新关键词:暂无标签

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 public class Codec { 2 ????private const string pref = "http://tinyurl.com/"; 3 ?????4 ????// in thoery should use a hash founction 5 ????private int counter = 0; 6 ????private Dictionary<int, string> hashToUrl = new Dictionary<int, string>(); 7 ????private Dictionary<string, int> urlToHash = new Dictionary<string, int>(); 8 ?????9 ????// Encodes a URL to a shortened URL10 ????public string encode(string longUrl) {11 ????????if (!urlToHash.ContainsKey(longUrl))12 ????????{13 ????????????urlToHash[longUrl] = counter;14 ????????????hashToUrl[counter] = longUrl;15 ????????????counter++; ???16 ????????}17 ????????18 ????????return pref + urlToHash[longUrl];19 ????}20 21 ????// Decodes a shortened URL to its original URL.22 ????public string decode(string shortUrl) {23 ????????int hash = Int32.Parse(shortUrl.Substring(19, shortUrl.Length - 19));24 ????????25 ????????return hashToUrl[hash];26 ????}27 }28 29 // Your Codec object will be instantiated and called as such:30 // Codec codec = new Codec();31 // codec.decode(codec.encode(url));

Leetcode 535: Encode and Decode TinyURL

原文地址:https://www.cnblogs.com/liangmou/p/8175547.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved