微软笔试题#1086 : Browser Caching LRC缓存实现

When you browse the Internet, browser usually caches some documents to reduce the time cost of fetching them from remote servers. Let’s consider a simplified caching problem. Assume the size of browser’s cache can store M pages. When user visits some URL, browser will search it in the cache first. If the page is already cached browser will fetch it from the cache, otherwise browser will fetch it from the Internet and store it in the cache. When the cache is full and browser need to store a new page, the least recently visited page will be discarded.

Now, given a user’s browsing history please tell us where did browser fetch the pages, from the cache or the Internet? At the beginning browser’s cache is empty.

输入

Line 1: Two integers N(1 <= N <= 20000) and M(1 <= M <= 5000). N is the number of pages visited and M is the cache size.

Line 2~N+1: Each line contains a string consisting of no more than 30 lower letters, digits and dots(‘.’) which is the URL of the page. Different URLs always lead to different pages. For example www.bing.com and bing.com are considered as different pages by browser.

输出

Line 1~N: For each URL in the input, output “Cache” or “Internet”.

提示

Pages in the cache before visiting 1st URL [null, null]

Pages in the cache before visiting 2nd URL [www.bing.com(1), null]

Pages in the cache before visiting 3rd URL [www.bing.com(1), www.microsoft.com(2)]

Pages in the cache before visiting 4th URL [www.bing.com(1), www.microsoft.com(3)]

Pages in the cache before visiting 5th URL [windows.microsoft.com(4), www.microsoft.com(3)]

The number in parentheses is the last visiting timestamp of the page.

样例输入

5 2
www.bing.com
www.microsoft.com
www.microsoft.com
windows.microsoft.com
www.bing.com

样例输出

Internet
Internet
Cache
Internet
Internet

这个题可以分析一下LRU缓存,就是最近访问的应该最晚被淘汰,最近未被访问的最早被淘汰,可以考虑链表实现。

那么,我们考虑一下就是这样几种情况:

1.访问的页面在缓存,则把当前访问页面放在链表头

2.访问的页面不在缓存,如果没有超过数目,则添加当前页面到链表头

3.访问的页面不在缓存,如果超过数目,添加当前页面到链表头,删除链表尾

刚好java中有个双向链表实现的数组LinkedList 正好用上

import java.util.*;
public class LRU {
    public static void main(String args[])
    {
    	Scanner in=new Scanner(System.in);
    	while(in.hasNextLine())
    	{
    		String[] line=in.nextLine().split(" ");
    		int n=Integer.valueOf(line[0]);
    		int m=Integer.valueOf(line[1]);
    		LinkedList<String> queue=new LinkedList<String>();
    		for(int i=0;i<n;i++)
    		{
    			String str=in.nextLine();
    			if(queue.contains(str))
    			{
    				queue.remove(str);
    				queue.addFirst(str);
    				System.out.println("Cache");
    			}
    			else
    			{
    				if(queue.size()==m)
    				{
    					queue.removeLast();
    					queue.addFirst(str);
    				}
    				else
    				{
    					queue.addFirst(str);
    				}
    				System.out.println("Internet");
    			}
    		}
    	}
    	in.close();
    }
}
点赞