JAVA 剑指offer 第二版 6

面试题 67:将字符串转化为整数

注意考虑正负数,非法字符,空字符串,溢出等问题。
    public static int TurnStringToNum(char[] st){
        if (st == null || st.length == 0){
            error = true;
            return 0;
        }
        boolean isneg = false;
        if (st[0] == '+'){
            return TurnStringToNum_core(st,1,isneg);
        }else if (st[0] == '-'){
            isneg = true;
            return TurnStringToNum_core(st,1,isneg);
        }else {
            return TurnStringToNum_core(st,0,isneg);
        }
    }
    public static int TurnStringToNum_core(char[] st,int index,boolean ifneg){
        int num = 0;
        for (int x = index;x<st.length;x++){
            if (st[x] > '9' || st[x] < '0'){
                error = true;
                return 0;
            }
            int flag = ifneg ? -1:1;
            num = num *10 + flag*(st[x]-'0');
            if ((ifneg && num < 0x80000000)|| (!ifneg && num>0x7FFFFFFF)){
                error = true;
                return 0;
            }
        }
        return num;
    }

面试题68:树中两个节点的最低公共祖先

二叉搜索树 判断当前节点与两个目标节点的大小关系,找到第一个在其之间的就是
带父指针的二叉树 转换为求两个链表的第一个公共节点问题
普通的二叉树

1.判断两个目标节点是否都在子树中,再在子树中判断,出现在子树中,但子树不满足的情况则找到第一个公共节

2.用两个链表保存从根到目标节点的路径,求最后一个公共节点。

    public static boolean getPath(Node target, Node head, LinkedList it){
       if (head == null || target == null){
           return false;
       }
       it.add(head);
       if (head.value == target.value){
           return true;
       }
       if (head.left!=null){
           if (getPath(target,head.left,it) == true){
               return true;
           }
       }
       if (head.right!= null){
           if (getPath(target,head.right,it) == true){
               return true;
           }
       }
       it.remove(it.size()-1);
       return false;
    }
    public static Node getLastCommon(LinkedList<Node> t1,LinkedList<Node> t2){
        if (t1 == null || t2 == null){
            return null;
        }
        int len1 = t1.size();
        int len2 = t2.size();
        int len = len1 > len2 ? len2:len1;
        int x = 0;
        for (;x<len;x++){
            if (t1.get(x) != t2.get(x)){
                break;
            }
        }
        return t1.get(x-1);

    }
    public static Node getFather(Node t1,Node t2,Node head){
        if (t1 == null || t2 == null || head == null ){
            return null;
        }
        LinkedList<Node> it1 = new LinkedList();
        LinkedList<Node> it2 = new LinkedList();
        getPath(t1,head,it1);
        getPath(t2,head,it2);

        return getLastCommon(it1,it2);
    }

猜你喜欢

转载自blog.csdn.net/u011010851/article/details/80346199