面试准备系列02----面试中的栈和队列题目汇总
本文是面试准备系列的第二篇文章,第一篇为《面试准备系列01----面试中的链表题目汇总》,下一篇为《面试准备系列03----面试中的二叉树题目汇总》。
1.栈的经典应用:括号匹配+表达式计算
http://blog.csdn.net/sheepmu/article/details/21563557
2.两个栈实现队列+两个队列实现栈
http://blog.csdn.net/sheepmu/article/details/38428205
3.实现包含最大最小值的栈O(1)
http://blog.csdn.net/sheepmu/article/details/38459165
4.Linux简化文件路径
题目:https://oj.leetcode.com/problems/simplify-path/
思路:以/分隔字符串,遇到 . 和 空格什么都不做,遇到..退栈,其他都进栈,最后把栈中的都用/连接起来就是简化后的路径
package com.sheepmu;
import java.util.Stack;
/**
* Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
click to show corner cases.
Corner Cases:
Did you consider the case where path = "/../"?
In this case, you should return "/".
Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
In this case, you should ignore redundant slashes and return "/home/foo".
* @author Sheep Mu
*
*/
public class SimplilyPath
{
public static void main(String[] args)
{
String path="/a/./b/../../c/";
String result=sp(path);
System.out.println(result);
}
public static String sp(String path)
{
if(path==null||path.length()==0)
return "";
String[] splits=path.split("/");
Stack<String> stack=new Stack<String>();
StringBuffer sb=new StringBuffer();
for(String ss:splits)
{
if(ss.equals(".")||ss.length()==0)//防止//的情况
continue;
else if(ss.equals(".."))
{
if(!stack.isEmpty())
stack.pop();
}
else
stack.push(ss);
}
if(!stack.isEmpty())
{//这里其实我们又需要把栈里面的内容先进先出了,所以还是用LinkedList方便,它可以同时实现栈和队列的方法
String[] as=stack.toArray(new String[stack.size()]);//不能toArray()后再强制转换,会报错
for(String sss:as)
sb.append("/"+sss);
}
else//stack为空,
{
sb.append("/");
}
return sb.toString();
}
}
5.二叉树的非递归前中后序遍历用Stack,层序遍历用Queue
http://blog.csdn.net/sheepmu/article/details/28941285
6.栈的压人、弹出序列(剑桥Offer22)
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。
package com.sheepmu;
import java.util.Stack;
public class Offer22 {
public static void main(String[] args)
{
int[] input={1,2,3,4,5};
int[] output={2,1,4,3,5};
if( isPopSequence(input,output))
System.out.println("true");
else
System.out.println("false");
}
public static boolean isPopSequence(int[] input,int[]output)
{
if(input==null||output==null)
return false;
if(input.length==0||output.length==0)
return false;
if(input.length!=output.length)
return false;
int len=input.length;
Stack<Integer> stack=new Stack<Integer>();
int i=0,j=0;
while(j<len)
{
if(i<len)
{
stack.push(input[i++]);
while(!stack.isEmpty()&&stack.peek()==output[j])
{
stack.pop();
j++;
}
}
else
return false;
}
return true;
}
}