Skip to content

Commit 3dd2830

Browse files
committed
5/31
1 parent e1db6d6 commit 3dd2830

File tree

1 file changed

+108
-0
lines changed

1 file changed

+108
-0
lines changed
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
Easy Leetcode 1160
2+
3+
tags: String
4+
5+
方法1:
6+
自己的方法纯intuitive没有用到复杂的数据结构就是命令式解法
7+
8+
方法2:
9+
自己思考改进之后的算法每次都用StringBuilder太消耗资源把判断contain改成了用hashmap提高效率
10+
11+
方法3
12+
网友的方法思路是一致的只不过没有用hashmap而是用了array去计算个数map这种计算count类的方法很多
13+
都可以转为array代码没有map清晰但是效率高了很多
14+
方法2用了55ms方法3才有9s可见开销差距
15+
16+
17+
```
18+
19+
/*
20+
方法1
21+
*/
22+
23+
class Solution {
24+
public int countCharacters(String[] words, String chars) {
25+
List<String> result = new ArrayList<>();
26+
for (String word : words) {
27+
boolean flag = true;
28+
StringBuilder tmp = new StringBuilder(chars);
29+
for (int j = 0; j < word.length(); j++) {
30+
Character x = word.charAt(j);
31+
int index = tmp.indexOf(x.toString());
32+
if ( index>= 0) {
33+
tmp.deleteCharAt(index);
34+
} else {
35+
flag = false;
36+
}
37+
}
38+
if (flag) {
39+
result.add(word);
40+
}
41+
}
42+
int res = 0;
43+
for (String s : result) {
44+
res += s.length();
45+
}
46+
return res;
47+
}
48+
}
49+
50+
/*
51+
方法2
52+
*/
53+
54+
public static int countCharacters(String[] words, String chars) {
55+
int res = 0;
56+
HashMap<Character, Integer> mapA = new HashMap<>();
57+
for (int i = 0; i < chars.length(); i++) {
58+
char x = chars.charAt(i);
59+
mapA.put(x, mapA.getOrDefault(x, 0) + 1);
60+
}
61+
for (String word : words) {
62+
HashMap<Character, Integer> map = (HashMap<Character, Integer>) mapA.clone();
63+
boolean flag = true;
64+
for (int j = 0; j < word.length(); j++) {
65+
char x = word.charAt(j);
66+
if ( map.getOrDefault(x, 0) > 0) {
67+
map.put(x, map.get(x) -1);
68+
} else {
69+
flag = false;
70+
}
71+
}
72+
if (flag) {
73+
res += word.length();
74+
}
75+
}
76+
return res;
77+
}
78+
79+
/*
80+
方法3
81+
*/
82+
83+
public static int countCharacters(String[] words, String chars) {
84+
int count = 0;
85+
int[] seen = new int[26];
86+
//Count char of Chars String
87+
for (char c : chars.toCharArray())
88+
seen[c - 'a']++;
89+
// Comparing each word in words
90+
for (String word : words) {
91+
// simple making copy of seen arr
92+
int[] tSeen = Arrays.copyOf(seen, seen.length);
93+
int Tcount = 0;
94+
for (char c : word.toCharArray()) {
95+
if (tSeen[c - 'a'] > 0) {
96+
tSeen[c - 'a']--;
97+
Tcount++;
98+
}
99+
}
100+
if (Tcount == word.length())
101+
count += Tcount;
102+
}
103+
return count;
104+
}
105+
106+
107+
108+

0 commit comments

Comments
 (0)