Skip to content

Commit 7adf928

Browse files
committed
Add Invert Binary Tree and Valid Anagram
1 parent 64c2351 commit 7adf928

File tree

3 files changed

+91
-0
lines changed

3 files changed

+91
-0
lines changed

src/com/andrewbayd/ValidAnagram.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.andrewbayd;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
/*
7+
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
8+
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
9+
10+
https://leetcode.com/problems/valid-anagram/
11+
*/
12+
13+
public class ValidAnagram {
14+
15+
public static boolean isAnagram(String s, String t) {
16+
Map<Character, Integer> map = new HashMap<>();
17+
18+
if (s.length() != t.length()) {
19+
return false;
20+
}
21+
22+
for (char c : s.toCharArray()) {
23+
map.put(c, map.getOrDefault(c, 0) + 1);
24+
}
25+
26+
for (char c : t.toCharArray()) {
27+
if (map.containsKey(c)) {
28+
map.put(c, map.get(c) - 1);
29+
} else {
30+
return false;
31+
}
32+
}
33+
for (int i : map.values()) {
34+
if (i != 0) return false;
35+
}
36+
return true;
37+
}
38+
39+
public static void main(String[] args) {
40+
System.out.println(isAnagram("anagram", "nagaram")); //-> true
41+
System.out.println(isAnagram("rat", "car")); //-> false
42+
}
43+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.andrewbayd.invertBinaryTree;
2+
3+
/*
4+
Given the root of a binary tree, invert the tree, and return its root.
5+
6+
https://leetcode.com/problems/invert-binary-tree/
7+
*/
8+
9+
public class Solution {
10+
11+
public TreeNode invertTree(TreeNode root) {
12+
invertRecursive(root);
13+
return root;
14+
15+
}
16+
17+
private void invertRecursive(TreeNode root) {
18+
if (root == null) {
19+
return;
20+
}
21+
TreeNode temp = root.left;
22+
root.left = root.right;
23+
root.right = temp;
24+
invertRecursive(root.left);
25+
invertRecursive(root.right);
26+
}
27+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.andrewbayd.invertBinaryTree;
2+
3+
// Definition for a binary tree node.
4+
public class TreeNode {
5+
int val;
6+
TreeNode left;
7+
TreeNode right;
8+
9+
TreeNode() {
10+
}
11+
12+
TreeNode(int val) {
13+
this.val = val;
14+
}
15+
16+
TreeNode(int val, TreeNode left, TreeNode right) {
17+
this.val = val;
18+
this.left = left;
19+
this.right = right;
20+
}
21+
}

0 commit comments

Comments
 (0)