【剑指offer第二版】JAVA刷题总结-ch7

67. 把字符串转成整数

思路:

  1. 判断是否是非法输入
  2. 忽略所有行首空格,找到第一个非空格字符,可以是 ‘+/−’ 表示是正数或者负数,紧随其后找到最长的一串连续数字,将其解析成一个整数;
  3. 整数后可能有任意非数字字符,请将其忽略;
  4. 如果整数长度为0,则返回0;
  5. 如果整数大于INT_MAX(2^31 − 1),请返回INT_MAX;如果整数小于INT_MIN(−2^31) ,请返回INT_MIN;
class Solution {
    boolean valid = true;
    public int strToInt(String str) {
        if(str==null){
            valid = false;
            return 0;
        }
        if(str.length()==0) return 0;
        int ans = 0;
        boolean negative = false;
        boolean positive = false;
        str = str.trim();
        for(int i=0; i<str.length(); i++){
            if(i==0){
                if(str.charAt(0)=='+'){
                    positive=true; 
                    continue;
                }
                else if(str.charAt(0)=='-'){
                    negative=true;
                    continue;
                }
            }
            if(str.charAt(i)>='0' && str.charAt(i)<='9'){
                if(ans*10+str.charAt(i)<ans){
                    if(negative==false) return Integer.MAX_VALUE;
                    else return Integer.MIN_VALUE;
                }
                ans = ans*10+(str.charAt(i)-'0');
                // System.out.println(ans);
            }
            if(str.charAt(i)<'0' || str.charAt(i)>'9'){
                if((positive || negative) && i>=2) continue;
                if((!positive && !negative) && i>=1) continue;
                valid = false;
                return 0;
            }
        }
        return negative?-ans:ans;
    }
}

68. 树种两个节点的最低公共祖先

思路:在左右子树中查找是否存在 p 或者 q,如果 p 和 q 分别在两个子树中,那么就说明根节点就是最低公共祖先。

  class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q)
            return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        return left == null ? right : right == null ? left : root;
    }
}
发布了16 篇原创文章 · 获赞 0 · 访问量 3118

猜你喜欢

转载自blog.csdn.net/Calliope1997/article/details/104334583
今日推荐