新浪笔试编程题二

来源:互联网 发布:网络暴力后果 编辑:程序博客网 时间:2024/05/21 13:57

  Java源文件source.java中含有“()”“{}”“[]”三种括号

1)  实现方法判断文件中括号是否正确匹配

2)  在此基础上,若不匹配输出行号和不匹配的括号类型。

思路:使用stack进行存储,若为右侧括号则入栈,若为左侧括号则出栈,并判断是否为一对相匹配括号,若匹配则继续直到将java源文件读取完毕,若不匹配则停止判断并输出判断结果

问题2在1的基础上增加一些代码即可,代码如下

public boolean isTrue(String filepath) throws IOException{
boolean flag = true;
File f = new File(filepath);
BufferedReader br = new BufferedReader(new FileReader(f));

String temp = "";
Stack<Character> stack = new Stack<>();
Lable:
while((temp = br.readLine())!=null){
for(int i = 0;i<temp.length();i++){
char ch = temp.charAt(i);
if (ch=='('||ch=='{'||ch=='[') {
stack.push(ch);
}
else if(ch==')'||ch=='}'||ch==']'){
if (stack.size()==0) {
flag = false;
break Lable;
}else{
char top = stack.pop();
if (top!=ch) {
flag = false;
break Lable;
}
}
}
}
}

return flag;
}
public boolean isTrue2(String filepath) throws IOException{
boolean flag = true;
File f = new File(filepath);
BufferedReader br = new BufferedReader(new FileReader(f));
int line  = 0;
String temp = "";
char ch = '0';
Stack<Character> stack = new Stack<>();
Lable:
while((temp = br.readLine())!=null){
line++;
for(int i = 0;i<temp.length();i++){
ch = temp.charAt(i);
if (ch=='('||ch=='{'||ch=='[') {
stack.push(ch);
}
else if(ch==')'||ch=='}'||ch==']'){
if (stack.size()==0) {
flag = false;
break Lable;
}else{
char top = stack.pop();
if (top!=ch) {
flag = false;

break Lable;
}
}
}
}
}

if (flag) {
System.out.println("全部匹配");
}else{
System.out.println("不匹配的行号为:"+line+",不匹配的括号为:"+ch);
}
return flag;
}

0 0
原创粉丝点击