-
- 用两个栈(stacks)来实现一个队列(queue),完成队列的push和pop操作。只能使用Stack的isEmpty()、push()与pop()三个操作。队列中的元素为int类型。
import java.util.Stack;
public class Solution {
private Stack<Integer> pushStack = new Stack<>();
private Stack<Integer> popStack = new Stack<>();
public void push(Integer value) {
pushStack.push(value);
}
public Integer pop() {
if (!popStack.isEmpty()) {
return popStack.pop();
}
while (!pushStack.isEmpty()) {
Integer temp = pushStack.pop();
popStack.push(temp);
}
if (popStack.isEmpty()) {
return null;
}
return popStack.pop();
}
public boolean isEmpty() {
return popStack.isEmpty() && pushStack.isEmpty();
}
public static void main(String[] args) {
Solution queue = new Solution();
for (int i = 0; i < 100; i++) {
queue.push(i);
}
System.out.println(queue.pop());
System.out.println(queue.pop());
while (!queue.isEmpty()) {
System.out.println(queue.pop());
}
}
}
-
- TinyURL是一个URL缩短服务,你可以输入一个URL像是https://leetcode.com/problems/design-tinyurl,然后这个服务会回传一个像是http://tinyurl.com/4e9iAk的短网址。请您为TinyURL设计其中的URL编码与解码函数。函数如何实现没有任何限制,但要确保一个URL要能编码为一个短网址,而此短网址要能解码成原本的网址。
package com.leno.jeep.simple.queue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
public class Codec {
private HashMap<String, String> map = new HashMap<>();
public String encode(String longUrl) {
for (HashMap.Entry<String, String> item : map.entrySet()) {
if (item.getValue().equals(longUrl)) {
return item.getKey();
}
}
String shortUrl = "";
while (map.get(shortUrl) != null) {
shortUrl = getShortRandomUrl();
}
map.put(shortUrl, longUrl);
return shortUrl;
}
public String decode(String shortUrl) {
return map.get(shortUrl);
}
public String getShortRandomUrl() {
String randomStr = "http://tinyurl.com/";
Random random = new Random();
for (int i = 0; i < 4; i++) {
int tempI = random.nextInt(36);
if (tempI < 10) {
randomStr = randomStr + tempI;
} else {
char tempC = (char) ('A' + tempI - 10);
randomStr = randomStr + tempC;
}
}
return randomStr;
}
public String getLongRandomUrl() {
String randomStr = "https://leetcode.com/problems/design-tinyurl/";
Random random = new Random();
for (int i = 0; i < 20; i++) {
int tempI = random.nextInt(36);
if (tempI < 10) {
randomStr = randomStr + tempI;
} else {
char tempC = (char) ('A' + tempI - 10);
randomStr = randomStr + tempC;
}
}
return randomStr;
}
public static void main(String[] args) {
Codec demo = new Codec();
List<String> urlList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
urlList.add(demo.getLongRandomUrl());
}
for (String item : urlList) {
System.out.println("原来的长链接:" + item);
String shortUrl = demo.encode(item);
System.out.println("短url:" + shortUrl);
String longUrl = demo.decode(shortUrl);
System.out.println("解码url:" + longUrl);
System.out.println("=======================");
}
}
}