华为的一道机试,你会吗,用java写出来

球球之家/carver 2013-09-11 10:08:25
...全文
2372 37 打赏 收藏 转发到动态 举报
写回复
用AI写文章
37 条回复
切换为时间正序
请发表友善的回复…
发表回复
慎为 2016-02-15
  • 打赏
  • 举报
回复
取出所有的[()], 如果是回文不就是0么
asddsaasd111 2014-10-16
  • 打赏
  • 举报
回复
import java.util.Scanner; public class Kuohao { static void match(String str){ String[] strs=str.split("[^\\[\\]()]"); String tmp=""; for(String s : strs){ tmp+=s; } System.out.println(tmp); int flagA=0; int flagB=0; for(int i=0;i<tmp.length();i++){ char ch=tmp.charAt(i); if(ch=='[') flagA++; else if(ch==']') flagA--; else if(ch=='(') flagB++; else if(ch==')') flagB--; if(flagA<0||flagB<0) break; } if(tmp.contains("[)")||tmp.contains("(]")||flagA!=0||flagB!=0){ System.out.println("1"); }else{ System.out.println("0"); } } public static void main(String[] args) { // TODO Auto-generated method stub Scanner ss = new Scanner(System.in); while(true){ match(ss.nextLine()); } } }
kly824968443 2013-09-18
  • 打赏
  • 举报
回复
public class Test { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.err.println(getBoolean(scanner.next())); } //判断一个字符串是否匹配()[]关系 private static boolean getBoolean(String string) { boolean bool = false; List<Character> charList = new LinkedList<Character>(); if(string.length()>0){ //将这个字符串中的所有()[]符号放到一个堆栈中 for(int i=0;i<string.length();i++){ if(string.charAt(i)=='('||string.charAt(i)==')'||string.charAt(i)=='['||string.charAt(i)==']'){ charList.add(string.charAt(i)); } } //判断这个堆栈中是否每个'('或'['符号后面是否紧跟一个')'或']'相匹配,如果存在,继续遍历,只要存在一个不匹配,直接返回false for (int i=1;i<charList.size();i++) { if((charList.get(i-1)=='(' && charList.get(i)!=')') || (charList.get(i-1)=='[' && charList.get(i)!=']')){ return false; } } return true; } return bool; } }
HUIQQ0927 2013-09-17
  • 打赏
  • 举报
回复
3、数组起始,不能为 ]、)
HUIQQ0927 2013-09-17
  • 打赏
  • 举报
回复
遍历字符串,是(和[,存入数组: 1、如果数组长度不是整数,返回 0 2、对折对比,都为真,返回 0,否则 1
harrisonkao 2013-09-17
  • 打赏
  • 举报
回复
貌似用栈不要几行代码就出来了吧
aben402 2013-09-16
  • 打赏
  • 举报
回复
String s="terminal user [no | name (1)]"; Stack<Character> stack = new Stack<Character>(); for (int i = 0; i < s.length(); i++) { char chx = s.charAt(i); switch (chx) { case '(': case '[': stack.push(chx); break; case ')': if (stack.isEmpty()) { stack.push(chx); } else { if (stack.pop() != '(') { System.out.println(1); return; } } break; case ']': if (stack.isEmpty()) { stack.push(chx); } else { if (stack.pop() != '[') { System.out.println(1); return; } } break; default: break; } } if (stack.isEmpty()) { System.out.println(0); }else { System.out.println(1); }
steely_chen 2013-09-16
  • 打赏
  • 举报
回复
话说这道题需要遍历吗?为什么不用正则表达式?
davidcoffee 2013-09-14
  • 打赏
  • 举报
回复

public static boolean checkIsBracketsTwining(String sourceString,
	    Character[] tags) {

	if (tags.length != 2)
	    return false;

	Stack<Character> stack = new Stack<Character>();
	boolean isValid = true;
	for (Character c : sourceString.toCharArray()) {

	    if (!stack.isEmpty() && stack.peek() == tags[0]
		    && c == tags[1]) {
		isValid = true;
		stack.pop();
	    } else {
		stack.push(c);
		isValid = !(c == tags[0] || c == tags[1]);
	    }
	}

	return isValid;
    }
下班时候网络不好每提交成功,看来已经倍解答玩了,思路就是栈的操作,碰到哦成对弹出去,然后判断
blackkettle 2013-09-12
  • 打赏
  • 举报
回复
引用 21 楼 sjlzcj 的回复:
我想说 上面几楼用JAVA的人 没有一个人关注了 内存限制128M的条件 只有那个C++哥注意了, 各位Javaer 们 咱们能不能静下心来不要这样的浮躁
+1
  • 打赏
  • 举报
回复
引用 21 楼 sjlzcj 的回复:
我想说 上面几楼用JAVA的人 没有一个人关注了 内存限制128M的条件 只有那个C++哥注意了, 各位Javaer 们 咱们能不能静下心来不要这样的浮躁
求正确答案。。。。。。
木_木_三 2013-09-12
  • 打赏
  • 举报
回复

	public static int testString(String input){
		int flag=0;
		//转化成char数组
		char[] oldChar=input.toCharArray();
		//new一个新数组 存放 "[" "(" ")" "]"
		char[] newChar=new char[oldChar.length];
		//遍历char数组 如果存在括号  则存入新的char[]中
		for(int i=0;i<oldChar.length;i++ ){
			if(oldChar[i] =='[' || oldChar[i] ==']' || oldChar[i] =='(' || oldChar[i] ==')'){
				newChar[flag]=oldChar[i];
				flag++;
			}
		}
		//将新的数组转换成String 如果String中存在连续的 "[]" 或者"()" 则返回1 否则返回0
		String result=new String(newChar);
		if(result.indexOf("[]") !=-1 || result.indexOf("()") != -1){
			return 1;
		}
			return 0;
	}
steely_chen 2013-09-12
  • 打赏
  • 举报
回复
引用 26 楼 yousteely 的回复:

public static void main(String[] args) {
	String str=args[0];
	String kuehaod = ".*(\\[\\]|\\(\\)).*"; //匹配有连续配对的括号
	String kuehaom = ".*(\\(|\\)|\\[|\\]).*"; //匹配有任意括号
        //如果有连续配对的括号直接回返0,没有的话就检查字符串有没有包括任意括号
	int result = str.matches(kuehaod)?0:str.matches(meikuehaom)?1:0;
	System.out.println(result);
}
args[0] 可以替换成你要测试的字符串
steely_chen 2013-09-12
  • 打赏
  • 举报
回复

public static void main(String[] args) {
	String str=args[0];
	String kuehaod = ".*(\\[\\]|\\(\\)).*"; //匹配有连续配对的括号
	String kuehaom = ".*(\\(|\\)|\\[|\\]).*"; //匹配有任意括号
        //如果有连续配对的括号直接回返0,没有的话就检查字符串有没有包括任意括号
	int result = str.matches(kuehaod)?0:str.matches(meikuehaom)?1:0;
	System.out.println(result);
}
想名费脑 2013-09-12
  • 打赏
  • 举报
回复
//括号错误情况(中间2位) ][ )( [) (] ]) )] ([
想名费脑 2013-09-12
  • 打赏
  • 举报
回复

string str = "qweqwe[])(wq";

if (str.IndexOf(')') > -1 && str.IndexOf('(') > -1 && str.IndexOf('[') > -1 && str.IndexOf(']') > -1)//[]()都有
{
        str.ToArray();
        int sum = 0;
        foreach (char c in str)
        {
            if (c == '[' || c == ']' || c == '(' || c == ')')
                sum++;
        }
        if (sum == 4)//括号没有重复
        {
            int[] arr = new int[4];
            arr[0] = str.IndexOf('[');
            arr[1] = str.IndexOf(']');
            arr[2] = str.IndexOf('(');
            arr[3] = str.IndexOf(')');
            int temp;
            for (int i = 1; i < arr.Length; i++)  //冒泡
            {
                for (int j = 0; j < arr.Length - i; j++)
                {
                    if (arr[j] > arr[j + 1])
                    {
                        temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                    }
                }
            }
            if (arr[1] == str.IndexOf(']') &&  arr[2] == str.IndexOf('['))//括号错误情况(中间2位) ][ )( [) (] 
                Console.WriteLine(1);
            else if(arr[1] == str.IndexOf(')') &&  arr[2] == str.IndexOf('('))
                Console.WriteLine(1);
            else if(arr[1] == str.IndexOf('[') &&  arr[2] == str.IndexOf(')'))
                Console.WriteLine(1);
            else if(arr[1] == str.IndexOf('(') &&  arr[2] == str.IndexOf(']'))
                Console.WriteLine(1);
            else
                Console.WriteLine(0);
        }
        else
            Console.WriteLine(1);
}
else if(str.IndexOf('[')<0 && str.IndexOf(']')<0 && str.IndexOf('(') < 0 && str.IndexOf(')') < 0)//没有括号
{
    Console.WriteLine(0);
}
else
    Console.WriteLine(1);
  • 打赏
  • 举报
回复
引用 5 楼 breaking236 的回复:
public int find(String inputstr){ String s; int a = 1; if(inputstr.contains("[")){ if(inputstr.contains("]")){ if(inputstr.indexOf("[") < inputstr.indexOf("}")){ s = inputstr.substring(inputstr.indexOf("["),inputstr.indexOf("}")+1); if(s.contains("(")){ if(s.contains(")")){ if(s.indexOf("(") < s.indexOf(")")){ a = 0; } else{ a = 1; } }else{ a = 1; } }else{ a = 1; } }else{ a = 1; } }else{ a = 1; } }else{ if(!inputstr.contains("]") && !inputstr.contains("(") && !inputstr.contains(")")) { a = 0; } } return a; } 数组的比较烦,思路差不多
你的思路也能做出来,不过比较容易出错
  • 打赏
  • 举报
回复
引用 6 楼 wq568907978 的回复:
public static int checkStr(String s){ int resultValue = 0; //初始返回值 LinkedList<Byte> ll= new LinkedList<Byte>(); //用于存放括号的栈 byte[] bs = s.getBytes(); //遍历String for(byte b : bs){ //如果是左括号,存入栈 if(b == '('||b == '['){ ll.add(b); }else if(b == ')'){ //如果是‘)’,取栈中最后的括号,判断是否匹配 //若不匹配,则返回1; if(ll.getLast() != '('){ resultValue = 1; break; } }else if(b == ']'){ if(ll.getLast() == '['){ resultValue = 1; break; } } } return resultValue; }
方法可行,比较清晰
public  int checkStr(String s){

		int resultValue = 0; // 初始返回值
		LinkedList<Byte> ll = new LinkedList<Byte>(); // 用于存放括号的栈
		byte[] bs = s.getBytes();
		// 遍历String
		for (byte b : bs) {
			// 如果是左括号,存入栈
			if (b == '(' || b == '[') {
				ll.add(b);
			} else if (b == ')') {
				// 如果是‘)’,取栈中最后的括号,判断是否匹配
				// 若不匹配,则返回1;
				if (ll.getLast() != '(') {
					resultValue = 1;
					break;
				}
			} else if (b == ']') {
				if (ll.getLast() != '[') {
					resultValue = 1;
					break;
				}
			}
		}
		return resultValue;
	}
S117 2013-09-11
  • 打赏
  • 举报
回复

	public static int isMatch(String str){
		int  result = 0;
		LinkedList<Character> list = new LinkedList<Character>();
		if(str != null && str.trim().length() > 0){
			char[] chars = str.toCharArray();
			for(Character c : chars){
				if(c == '[' || c == '('){
					list.push(c);
				}
				if(c == ')'){
					Character character = list.pop();
					if(!(character == '(')){
						result = 1;
						break;
					}
				}
				if(c == ']'){
					Character character = list.pop();
					if(!(character == '[')){
						result = 1;
						break;						
					}					
				}
			}
		}
		if(list.size() > 0){
			result = 1;
		}
		return result;
	}
  • 打赏
  • 举报
回复
引用 5 楼 breaking236 的回复:
public int find(String inputstr){

public class testHuawei {
	public static void main(String[] args) {
		testHuawei t=new testHuawei();
		System.out.println(t.find("asdlfjh{(})"));
		System.out.println(t.find("asdlfjh"));
		System.out.println(t.find("asdlfjh()"));
	}
	
	public  int find(String inputstr){
        String s;
        int a = 1;
        if(inputstr.contains("[")){
            if(inputstr.contains("]")){
                if(inputstr.indexOf("[") < inputstr.indexOf("}")){
                s = inputstr.substring(inputstr.indexOf("["),inputstr.indexOf("}")+1);
                if(s.contains("(")){
                    if(s.contains(")")){
                        if(s.indexOf("(") < s.indexOf(")")){
                            a = 0;
                        }
                        else{
                            a = 1;
                        }
                    }else{
                        a = 1;
                    }
                }else{
                    a = 1;
                }
                }else{
                    a = 1;
                }
            }else{
                a = 1;
            }
        }else{
            if(!inputstr.contains("]") && !inputstr.contains("(") && !inputstr.contains(")"))
            {
                a = 0;
            }
        }
        return a;

    }
}
运行结果101,正确的是100
加载更多回复(17)

50,528

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧