面试题49:把字符串转换成整数
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。
public class Solution {
public int StrToInt(String str) {
if (str==null) {
try {
throw new NullPointerException("str is null.");
} catch (NullPointerException e) {
e.printStackTrace();
}
}
if (str.length()==0) {
return 0;
}
char[] chs = str.toCharArray();
int result = 0;
int n=0;
boolean flag = true;
if (chs[n]=='+') {
flag = true;
n++;
}else if (chs[n]=='-') {
flag = false;
n++;
}else if (chs[n]<'0'||chs[n]>'9') {
return 0;
}
while (n<chs.length&&chs[n]=='0') {
n++;
}
for (int i = n; i < chs.length; i++) {
if (chs[i]<'0'||chs[i]>'9') {
return 0;
}
result = result*10+(chs[i]-48);
}
if (!flag) {
result *= -1;
}
return result;
}
}
面试题50:树中两个节点的最低公共祖先
import java.util.Stack;
public class Demo50 {
//求最低公共祖先
public TreeNode GetLastCommonParent(TreeNode root,
TreeNode treenode1,TreeNode treenode2){
if (root==null||treenode1==null||treenode2==null) {
return null;
}
Stack<TreeNode> stack1 = new Stack<>();
Stack<TreeNode> stack2 = new Stack<>();
boolean treenodeflag1 = false;
boolean treenodeflag2 = false;
treenodeflag1 = GetNodePath(root, treenode1, stack1);
treenodeflag2 = GetNodePath(root, treenode2, stack2);
if (treenodeflag1&&treenodeflag2) {//如果都找到了两条路径
return GetLastCommonNode(stack1,stack2);
}
return null;
}
//求各个节点的路径
public boolean GetNodePath(TreeNode root,TreeNode node,Stack<TreeNode> stack){
//说明找到该路径了
if (root==node) {
return true;
}
//如果是叶节点了
if (root.left==null&&root.right==null) {
return false;
}
//入栈
stack.push(root);
boolean foundleft = false;
boolean foundright = false;
if (root.left!=null) {
foundleft = GetNodePath(root.left,node,stack);
if (foundleft) {
return true;
}
}
if (root.right!=null) {
foundright = GetNodePath(root.right,node,stack);
if (foundright) {
return true;
}
}
if (!foundleft&&!foundright) {
stack.pop();
}
return false;
}
/**
* 查找最后一个公共节点
* @param stack1
* @param stack2
* @return
*/
public TreeNode GetLastCommonNode(Stack<TreeNode> stack1,Stack<TreeNode> stack2){
TreeNode lastNode=null;
while (!stack1.isEmpty()&&!stack2.isEmpty()) {
TreeNode node1 = stack1.pop();
TreeNode node2 = stack2.pop();
if (node1==node2) {
lastNode = node1;
}
}
return lastNode;
}
}