LeetCode--Jewels and Stones && Range Sum of BST (Easy) 771. Jewels and Stones (Easy)# 938. Range Sum of BST(Easy)#
You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A".
Example 1:
Input: J = "aA", S = "aAAbbbb"
Output: 3
Example 2:
Input: J = "z", S = "ZZ"
Output: 0
Note:
S and J will consist of letters and have length at most 50.
The characters in J are distinct.
solution##
class Solution {
public int numJewelsInStones(String J, String S) {
int count=0;
for(int i=0; i<J.length(); i++)
{
for(int j=0; j<S.length(); j++)
{
if(J.charAt(i) == S.charAt(j))
count++;
}
}
return count;
}
}
总结##
此题思路较简单,用两个循环加一个计数器count解决即可,外层循环遍历J,内层循环遍历S。先取J里面的一个字符与S里面的字符挨个比较,如果两字符相同,计数器count++,否则什么都不做,这样直至循环结束。
938. Range Sum of BST(Easy)#
Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).
The binary search tree is guaranteed to have unique values.
Example 1:
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32
Example 2:
Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
Output: 23
Note:
The number of nodes in the tree is at most 10000.
The final answer is guaranteed to be less than 2^31.
solution##
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int rangeSumBST(TreeNode root, int L, int R) {
int leftsum = 0; int rightsum = 0;
if (root.left != null)
leftsum = rangeSumBST(root.left,L,R);
if (root.right != null)
rightsum = rangeSumBST(root.right,L,R);
if (L <= root.val && root.val <= R)
return root.val + leftsum + rightsum;
return leftsum + rightsum;
}
}
总结##
此题为二叉树结点值求和的升级版。整体思想为先求左子树结点值大于L小于R的和,再求右子树结点值大于L小于R的和,最后,如果根结点值大于L小于R,则加上根结点值。
首先定义两个int变量leftsum和rightsum用来分别存放左右子树的和,如果左子树非空,则递归求左子树结点值的和leftsum,如果右子树非空,则递归求右子树结点值的和rightsum。最后,如果根结点值大于L小于R,则加上根结点值并返回,否则,只返回leftsum+rightsum的值。
求二叉树结点里面值(假设为int)的和
public int sumBST(TreeNode root)
{
int leftsum = 0; int rightsum = 0;
if (root.left != null)
leftsum = sumBST(root.left);
if (root.right != null)
rightsum = sumBST(root.right);
return root.val + leftsum + rightsum;
}