Reverse String
原题目:
Write a function that takes a string as input and returns the string reversed.

事例:
Example:
Given s = "hello", return "olleh".
思路:
这个题还是非常简单的,主要的想法就是:
1、反向遍历一个字符串;
2、遍历出来的字节再按顺序拼接在一起返回。
自己的代码实现:
package com.mianshi.suanfa.ReverseString;
/**
* Created by macbook_xu on 2018/3/22.
*/
public class Solution {
public static String reverseString(String s) {
int j = 0;
String rs = "";
for (int i=s.length()-1 ; i>=0 ; i--){
rs += s.charAt(i);
j++;
}
return rs;
}
public static void main(String[] args) {
System.out.println(reverseString("hello"));
}
}
这里主要是使用了一个字符串的方法,charAt(),这个方法用来检索字符串中给定索引的字符,反转字符串是一个面试题中比较简单的算法实现,逻辑比较简单,也比较好实现,当然,StringBuilder有自带的反转函数,可以把字符串放到StringBuilder中调用reverse()方法,然后toString返回,但是在面试中面试官一般不会让你使用jdk自带的方法,嘿嘿,是不是很痛苦?
这个题确实很简单,就不加其他大神们的代码了,因为简单,所以今天还是应该多做一个的。
Merge Two Binary Trees
原题目:
Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.
翻译后:
给定两棵二叉树并设想当你将其中一棵覆盖另一棵时,两棵树的某些节点重叠,而其他树不重叠。
您需要将它们合并到一个新的二叉树中。合并规则是,如果两个节点重叠,则将节点值合计为合并节点的新值。否则,非空节点将被用作新树的节点。
自己理解:
虽然学数据结构的时候学习过二叉树,会深度与广度遍历啊什么的,但是,拿到这个题的时候我还是懵逼的,虽然理解了意思,就是从根结点开始合并,如果在对应位置的节点上,两个二叉树都有值,就相加作为这个节点的新值;如果只有一棵树在这个节点上有值,则这个值作为合并后的值;如果两颗数在此节点上都为空,则合并后的二叉树在这个节点也为空。但是真的把它变成代码,一点思路都没有,给大家看一下事例:
Example 1:
Input: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 Output: Merged tree: 3 / \ 4 5 / \ \ 5 4 7
Note: The merging process must start from the root nodes of both trees.
当然,题目还给出了一个默认的类:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
这个类主要有一个构造方法,传如当前节点的值,然后还有这个节点的左右孩子这两个变量。
因为自己比较菜没有做出来,所以学习了一下大神们的代码:
public class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) return null;
int val = (t1 == null ? 0 : t1.val) + (t2 == null ? 0 : t2.val);
TreeNode newNode = new TreeNode(val);
newNode.left = mergeTrees(t1 == null ? null : t1.left, t2 == null ? null : t2.left);
newNode.right = mergeTrees(t1 == null ? null : t1.right, t2 == null ? null : t2.right);
return newNode;
}
}
这段代码主要是通过递归调用,先把当前节点上两颗数的值相加,作为新节点的值存进去,然后调用自身的这个方法,传入左右孩子的值继续计算,直到最后左右孩子都为空时,最后成为一棵树返回。
当然,还有思路表达更清晰一些的代码:
public class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if(t1 == null && t2 == null) return null;
else if(t1 == null) return t2;
else if(t2 == null) return t1;
TreeNode n= new TreeNode(t1.val+t2.val);
n.left=mergeTrees(t1.left, t2.left);
n.right=mergeTrees(t1.right, t2.right);
return n;
}
}
这样看着是不是简单易读一些,嘿嘿,但是思想和方法基本上都是一样的。今天做题主要学到了很多逻辑上处理问题的方法,真是非常满足。