Skip to content

Commit 55b8a79

Browse files
committed
week02 second commit
1 parent 7507557 commit 55b8a79

4 files changed

Lines changed: 101 additions & 0 deletions

File tree

Week02/com/mypractice/Anagram.java

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.mypractice;
2+
3+
import java.util.Arrays;
4+
5+
public class Anagram {
6+
public boolean isAnagram1(String s, String t) {
7+
8+
if (s.length() != t.length()) {
9+
return false;
10+
}
11+
//使用暴力解法,将得到的两个字符串进行排序后比较是否相同
12+
char[] str1 = s.toCharArray();
13+
char[] str2 = t.toCharArray();
14+
Arrays.sort(str1);
15+
Arrays.sort(str2);
16+
return Arrays.equals(str1, str2);
17+
}
18+
19+
public boolean isAnagram2(String s, String t) {
20+
if (s.length() != t.length()) {
21+
return false;
22+
}
23+
//使用数组缓存字母元素,在s中出现时给元素+1,在t中出现时给元素-1
24+
//最后检查数组元素是否均为0
25+
int[] counter = new int[26];
26+
for (int i = 0; i < s.length(); i++) {
27+
counter[s.toLowerCase().charAt(i)-'a']++;
28+
counter[t.toLowerCase().charAt(i)-'a']--;
29+
}
30+
for (int count : counter) {
31+
if (count != 0) {
32+
return false;
33+
}
34+
}
35+
36+
return true;
37+
}
38+
39+
public static void main(String[] args) {
40+
String s="Aa";
41+
System.out.println((s.charAt(0)-'a'));
42+
System.out.println((s.charAt(1)-'a'));
43+
44+
}
45+
46+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.mypractice;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
public class BinaryTreeInorder {
7+
public List<Integer> inorderTraversal(TreeNode root) {
8+
List<Integer> result=new ArrayList<>();
9+
helper(root, result);
10+
return result;
11+
12+
}
13+
14+
public void helper(TreeNode root, List<Integer> result) {
15+
if (root != null) {
16+
if (root.left != null) {
17+
helper(root.left,result);
18+
}
19+
result.add(root.val);
20+
if (root.right != null) {
21+
helper(root.right,result);
22+
}
23+
}
24+
}
25+
26+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package com.mypractice;
2+
3+
4+
public class TreeNode {
5+
int val;
6+
TreeNode left;
7+
TreeNode right;
8+
9+
TreeNode(int x) {
10+
val = x;
11+
}
12+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.mypractice;
2+
3+
public class UglyNumber {
4+
public int nthUglyNumber(int n) {
5+
//我们将前面求得的丑数记录下来,后面的丑数就是前面的丑数*2,*3,*5
6+
int p2=0,p3=0,p5=0;
7+
int[] dp=new int[n];
8+
dp[0]=1;
9+
for(int i=1;i<n;i++){
10+
dp[i]=Math.min(dp[p2]*2,Math.min(dp[p3]*3,dp[p5]*5));
11+
if(dp[i]==dp[p2]*2) p2++;
12+
if(dp[i]==dp[p3]*3) p3++;
13+
if(dp[i]==dp[p5]*5) p5++;
14+
}
15+
return dp[n-1];
16+
}
17+
}

0 commit comments

Comments
 (0)