1. 38. Count and Say
就是对于前一个数,找出相同元素的个数,把个数和该元素存到新的string里。数量+字符
class Solution {
public String countAndSay(int n) {
if( n == 1)
return "1";
StringBuffer sb = new StringBuffer();
String str = countAndSay(n - 1); int count = 0;
char c = '0';
for( int i = 0; i < str.length(); i++ ){
c = str.charAt(i);
count = 1;
while((i+1) < str.length() && str.charAt(i) == str.charAt(i+1)){
count++;
i++;
}
sb.append(count + "" + c);
}
return sb.toString();
}
}
2. 58. Length of Last Word
String.lastIndexOf();
;1 class Solution {
public int lengthOfLastWord(String s) {
s = s.trim();
int lastIndex = s.lastIndexOf(' ') + 1;
return s.length() - lastIndex;
}
}
3. 100. Same Tree
采用递归的方法,return中逻辑的运用。
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if( p == null & q == null) return true;
if( p == null || q == null) return false;
if(p.val == q.val)
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
return false;
}
}