Leetcode 4.28 string

1. 38. Count and Say

  就是对于前一个数,找出相同元素的个数,把个数和该元素存到新的string里。数量+字符

 1 class Solution {
 2     public String countAndSay(int n) {
 3         if( n == 1)
 4             return "1";
 5         StringBuffer sb = new StringBuffer();
 6         String str = countAndSay(n - 1);
 7         
 8         int count = 0;
 9         char c = '0';
10         for( int i = 0; i < str.length(); i++ ){
11             c = str.charAt(i);
12             count = 1;
13             while((i+1) < str.length() && str.charAt(i) == str.charAt(i+1)){
14                 count++;
15                 i++;
16             }
17             sb.append(count + "" + c);
18         }
19         return sb.toString();
20     }
21 }

2. 58. Length of Last Word

  String.lastIndexOf();

;1 class Solution {
2     public int lengthOfLastWord(String s) {
3         s = s.trim();
4         int lastIndex = s.lastIndexOf(' ') + 1;
5         return s.length() - lastIndex;
6     }
7 }

3. 100. Same Tree

  采用递归的方法,return中逻辑的运用。

1 class Solution {
2     public boolean isSameTree(TreeNode p, TreeNode q) {
3         if( p == null & q == null) return true;
4         if( p == null || q == null) return false;
5         if(p.val == q.val)
6             return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
7         return false;
8     }
9 }

猜你喜欢

转载自www.cnblogs.com/Afei-1123/p/10783091.html