535 Encode and Decode TinyURL
2017-03-16 11:03
537 查看
url 长短两个类型的转化,初一看题意并不明确,不知道是否要保留http://
但参考了别人的答案后发现,其实并不需要,就是相当于一个长字符串和短字符串 之间建立一一对应的关系,其实就相当于字符和index之间的对应关系,稍微扩展一下就是这道题的解法的。
用动态array,ArrayList 就可以解决问题。代码如下,这里把index当作shortUrl比用size当作shortUrl更方便,测试过速度,70% vs 30%
public class Codec {
List<String> urls = new ArrayList<>();
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
urls.add(longUrl);
return String.valueOf(urls.size()-1);
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
int index= Integer.valueOf(shortUrl);
return index<urls.size()?urls.get(index):""; // 注意写法:先有return,再+判断条件,+ 肯定选项,+ : 否定选项
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));
但参考了别人的答案后发现,其实并不需要,就是相当于一个长字符串和短字符串 之间建立一一对应的关系,其实就相当于字符和index之间的对应关系,稍微扩展一下就是这道题的解法的。
用动态array,ArrayList 就可以解决问题。代码如下,这里把index当作shortUrl比用size当作shortUrl更方便,测试过速度,70% vs 30%
public class Codec {
List<String> urls = new ArrayList<>();
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
urls.add(longUrl);
return String.valueOf(urls.size()-1);
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
int index= Integer.valueOf(shortUrl);
return index<urls.size()?urls.get(index):""; // 注意写法:先有return,再+判断条件,+ 肯定选项,+ : 否定选项
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));
相关文章推荐
- python--leetcode 535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- HashTable-535-Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- 【LeetCode】535. Encode and Decode TinyURL
- leetcode题解-535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- leetcode 535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- Leetcode 535 Encode and Decode TinyURL
- leetcode535 Encode and Decode TinyURL java
- LeetCode 535 Encode and Decode TinyURL (HashMap)
- leetcode 535. Encode and Decode TinyURL
- LeetCode 535: Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- Leetcode 535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- LeetCode 535. Encode and Decode TinyURL对随机编码的思考