
获得徽章 3
- #每日一题# 二进制加法
String a = "11";
String b = "10";
StringBuffer str = new StringBuffer();
int lena = a.length();
int lenb = b.length();
int l = 0;
int t = 0;
int e = 0;
while(l<lena||l<lenb){
if(l<lena&&l<lenb)
e = a.charAt(lena-l-1)-'0' + b.charAt(lenb-l-1)-'0' + t;
else if(l<lena)e = a.charAt(lena-l-1)-'0' + t;
else if(l<lenb)e = b.charAt(lenb-l-1)-'0' + t;
if(e==3){
str.append('1');
e = 1;
}else if(e==2){
str.append('0');
e = 1;
}else if(e==1){
str.append('1');
e = 0;
}else{
str.append('0');
e = 0;
}
l++;
}
if(e==1)str.append('1');
System.out.println(str.reverse().toString());展开评论点赞 - #每日一题#
20.有效的括号
public boolean isValid(String s) {
HashMap<Character,Character> map = new HashMap<Character,Character>();
map.put('(',')');
map.put('{','}');
map.put('[',']');
map.put('?','?');//放置map中找不到,报出空指针异常
int len = s.length();
Stack<Character> stack = new Stack<Character>();
stack.add('?');
if(len==1)return false;
for(int i=0;i<len;i++){
if(map.containsKey(s.charAt(i)))stack.push(s.charAt(i));
else{
if(s.charAt(i)==map.get(stack.peek())){
stack.pop();
}
else {
return false;
}
}
System.out.println(stack.size());
}
return stack.size()==1;
}展开评论点赞 - #每日一题#
复杂链表拷贝,吧拷贝好的结点首先放入map中,之后再去递归其next,random结点,先放集合中证明已经拷贝了,不然会死循环
class Solution {
Map<Node, Node> map = new HashMap<Node, Node>();
public Node copyRandomList(Node head) {
if(head==null)return null;
if(!map.containsKey(head)){
Node node = new Node(head.val);
map.put(head,node);
node.next = copyRandomList(head.next);
node.random = copyRandomList(head.random);
return node;
}else {
return map.get(head);
}
}
}展开评论点赞 - #每日一题#
剑指 Offer II 056. 二叉搜索树中两个节点之和
class Solution {
Set<Integer> set = new HashSet<Integer>();
public boolean findTarget(TreeNode root, int k) {
if(root==null)return false;
if(set.contains(k-root.val))return true;
else {
set.add(root.val);
}
return findTarget(root.left, k) || findTarget(root.right, k);
}
}展开评论点赞 - #每日一题# 非递归前中后序遍历二叉树
前序中序代码相似,while一直遍历左节点,为空后就走一步右节点,继续while遍历左节点。差别就是输出根节点的位置不同。
难得是后序,先把子节点都放入栈,且以右左顺序放入,之后出栈遍历
public static ArrayList postOrder1(TreeNode root){
ArrayList alist = new ArrayList();
Stack<TreeNode> stack = new Stack<TreeNode>();
if(root == null)
return alist;
TreeNode cur,pre = null;
stack.push(root);
while(!stack.empty()){
cur = stack.peek();
if((cur.left == null && cur.right == null) || (pre != null && (cur.left == pre || cur.right == pre))){
TreeNode temp = stack.pop();
alist.add(temp.val);
pre = temp;
}
else{
if(cur.right != null)
stack.push(cur.right);
if(cur.left != null)
stack.push(cur.left);
}
}
return alist;
}展开评论点赞