您的位置:首页 > 职场人生

剑指Offer面试题49字符串转整数,面试题50二叉树两个结点的最低公共祖先

2017-08-17 18:50 1136 查看

面试题49:字符串转整数

这里的整数是指int,要考虑的问题如下:

1,输入null或空串;

2,正负号;

3,非法字符;

4,int越界(所以返回类型定义为long)。

Java实现如下:

public class StrToInt {
public static long str2int(String str) throws Exception{
if(str == null || str.length() == 0)
throw new Exception("null or empty");
long number = 0; // 要返回的int值
boolean minus = false; // 是否为负
int index = 0; // str下标
// 首位是否有正负号
if(str.charAt(index) == '+')
index++;
else if(str.charAt(index) == '-'){
index++;
minus = true;
}
// 如果首位有正负号,判断字符长度是否大于1,大于1或者首位不是正负号的话就接着执行
if(index < str.length()){
int flag = minus ? -1 : 1;
while(index < str.length()){
// 判断非法输入
if(str.charAt(index) >= '0' && str.charAt(index) <= '9'){
int digit = str.charAt(index) - '0';
number = number * 10 + flag * digit;
index++;
// 判断int越界
if((!minus && number > Integer.MAX_VALUE) || (minus && number < Integer.MIN_VALUE))
throw new Exception("out of the int maximum or minimum");
}else
throw new Exception("wrong input format");
}
}else
throw new Exception("only '+' or '-', no more number");
return number;
}
public static void main(String[] args) throws Exception {
System.out.println(str2int("-123"));
}
}


面试题50:二叉树两个结点的最低公共祖先

思路:先从根结点开始遍历二叉树,得到两个结点的路径,看作链表,两个链表的第一个公共结点就是最低公共祖先。

Java实现如下:

import java.util.Iterator;
import java.util.LinkedList;

class Node{
String value;
Node left;
Node right;
public Node(String value){
this.value = value;
}
}
public class GetLastCommonParent {

static Node getLastCommonParent(Node root, Node pNode1, Node pNode2){
if (root == null || pNode1 == null || pNode2 == null)
return null;
Node lastCommonNode = null;
LinkedList<Node> path1 = new LinkedList<Node>();
LinkedList<Node> path2 = new LinkedList<Node>();
getNodePath(root, pNode1, path1);
getNodePath(root, pNode2, path2);
Iterator<Node> iterator1 = path1.iterator();
Iterator<Node> iterator2 = path2.iterator();
while (iterator1.hasNext() && iterator2.hasNext()) {
Node iterator1Node = iterator1.next();
Node iterator2Node = iterator2.next();
if (iterator1Node == iterator2Node)
lastCommonNode = iterator1Node;
}
return lastCommonNode;
}

// 递归找路径,前序法,找到了返回true
static boolean getNodePath(Node root, Node p, LinkedList<Node> list) {
if (root == p) {
list.add(root);
return true;
}
list.add(root);
boolean found = false;
if (root.left != null)
found = getNodePath(root.left, p, list);
if (!found && root.right != null)
found = getNodePath(root.right, p, list);
if (!found)
list.remove(list.size() - 1);
return found;
}
public static void main(String[] args) {
Node a = new Node("A");
Node b = new Node("B");
Node c = new Node("C");
Node d = new Node("D");
Node e = new Node("E");
Node f = new Node("F");
Node g = new Node("G");
/*
*       a
*    b     c
*  d   e
* f g
*/
a.left = b;
a.right = c;
b.left = d;
b.right = e;
d.left = f;
d.right = g;
Node lastCommon = getLastCommonParent(a, f, e);
System.out.println(lastCommon.value);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息