您的位置:首页 > 其它

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));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: