Skip to content

Commit 1a4a60a

Browse files
authored
Week 02 Homework
1 parent cbc5e25 commit 1a4a60a

File tree

4 files changed

+86
-0
lines changed

4 files changed

+86
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
public List<Integer> preorderTraversal(TreeNode root) {
3+
List<Integer> res = new ArrayList<>();
4+
helper(root, res);
5+
return res;
6+
}
7+
8+
public void helper(TreeNode root, List<Integer> res) {
9+
if (root != null) {
10+
res.add(root.val);
11+
if (root.left != null) {
12+
helper(root.left, res);
13+
}
14+
if (root.right != null) {
15+
helper(root.right, res);
16+
}
17+
}
18+
}
19+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
public boolean isAnagram(String s, String t) {
3+
if(s.length() != t.length()) return false;
4+
5+
int[] counter = new int[26];
6+
for (int i = 0; i < s.length(); i++) {
7+
counter[s.charAt(i) - 'a']++;
8+
}
9+
10+
for (int i = 0; i < t.length(); i++) {
11+
counter[t.charAt(i) - 'a']--;
12+
if(counter[t.charAt(i) - 'a'] < 0){
13+
return false;
14+
}
15+
}
16+
17+
return true;
18+
}
19+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution {
2+
public List<List<String>> groupAnagrams(String[] strs) {
3+
if (strs.length == 0) {
4+
return new ArrayList<>();
5+
}
6+
7+
Map<String, List<String>> ans = new HashMap<>();
8+
9+
for (String str : strs) {
10+
char[] ch = str.toCharArray();
11+
Arrays.sort(ch);
12+
String key = String.valueOf(ch);
13+
if (!ans.containsKey(key)) {
14+
ans.put(key, new ArrayList<>());
15+
}
16+
ans.get(key).add(str);
17+
}
18+
return new ArrayList<>(ans.values());
19+
}
20+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
class Solution {
11+
public List<Integer> inorderTraversal(TreeNode root) {
12+
List<Integer> res = new ArrayList<>();
13+
helper(root, res);
14+
return res;
15+
}
16+
17+
public void helper(TreeNode root, List<Integer> res) {
18+
if (root != null) {
19+
if (root.left != null) {
20+
helper(root.left, res);
21+
}
22+
res.add(root.val);
23+
if (root.right != null) {
24+
helper(root.right, res);
25+
}
26+
}
27+
}
28+
}

0 commit comments

Comments
 (0)