zoukankan      html  css  js  c++  java
  • 今天面试问了一道题。说一串字符串由这几个符号组成"<>{}[]()”,写一个算法,例如如果组成方式为“<>{[]}{}()”这种,也就是XML格式那种则返回true。否则返回false;

    原创

    今天面试问了一道题。说一串字符串由这几个符号组成"<>{}[]()”,写一个算法,例如如果组成方式为“<>{[]}{}()”这种,也就是XML格式那种则返回true。否则返回false;

    当时没想出来, 只想到了回文数解决办法。回文数解决办法是颠倒比较,相等为true;

    换xml格式当时真没想到啥好方法;

    在回来的路上想到了。。

    。。

    去重,吧临近的一组去掉,在递归调用比较去重直到最后,如果有剩下则不返回false;否则true;

    代码为

    package hao;
    
    import java.util.HashMap;
    import java.util.Map;
    
    public class duichenpanduan {
    
        public static String a = "<>{><}(<<>><>)";
        public static Map<String, String> map = new HashMap<>();
    
        public static void main(String[] args) {
            map.put("<", ">");
            map.put("{", "}");
            map.put("[", "]");
            map.put("(", ")");
            System.out.println(test(a, a));
        }
    
        public static boolean test(String a1, String a2) {
            for (int i = 0; i < a1.length() - 1; i++) {
                String c = a1.charAt(i + 1) + "";
                String b = map.get(a1.charAt(i) + "");
                if (c.equals(b)) {
                    String a = a1.replaceFirst("\" + a1.charAt(i) + "\" + a1.charAt(i + 1), "");
                    System.out.println("去对称前=" + a1);
                    System.out.println("去对称后=" + a);
                    if(a.equals("")){
                        return  true;
                    }else if ( !a.equals(a1) || a.length() % 2 != 0) {
                        return test(a, a1);
                    } 
                }
            }
            return false;
        }
    }
    String a = "<>{}(<<>><>)";的比较结果

    String a = "<>{}(<<>><>)";的比较结果

    可能写的有些麻烦,欢迎指正,有更好的方法欢迎赐教;
    
    
    
  • 相关阅读:
    HTML5与HTML的区别
    0918练习整理
    0904 未来展望
    ajax弹出窗口
    AjAX请求后台,无刷新更新页面
    Jquery通过Ajax方式来提交Form表单
    php的socket通信
    次短路[SPFA]
    [Usaco2008 Open]Roads Around The Farm分岔路口[水题]
    [Usaco2008 Nov]Guarding the Farm 保卫牧场[DFS]
  • 原文地址:https://www.cnblogs.com/hao66/p/6973270.html
Copyright © 2011-2022 走看看