Skip to content

Commit a1c2769

Browse files
authored
Merge pull request gzc426#151 from V1ncentzzZ/master
LeetCode 打卡
2 parents 7c63e5b + 3c0da5a commit a1c2769

File tree

3 files changed

+87
-0
lines changed

3 files changed

+87
-0
lines changed
File renamed without changes.
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// TODO 执行比较慢,有冗余代码,待优化 7ms
2+
public int compress(char[] chars) {
3+
if(chars.length == 0) return 0;
4+
char temp = chars[0];
5+
int count = 0;
6+
int len = 0;
7+
for(int i=0; i<chars.length; i++){
8+
if(chars[i] == temp) count++;
9+
if(chars[i] != temp){
10+
chars[len++] = temp;
11+
if(count > 1){
12+
char[] step = String.valueOf(count).toCharArray();
13+
chars[len++] = step[0];
14+
if(count > 9) chars[len++] = step[1];
15+
}
16+
temp = chars[i];
17+
count = 1;
18+
}
19+
if(i == chars.length - 1) {
20+
chars[len++] = temp;
21+
if(count > 1){
22+
char[] step = String.valueOf(count).toCharArray();
23+
chars[len++] = step[0];
24+
if(count > 9) chars[len++] = step[1];
25+
}
26+
continue;
27+
}
28+
}
29+
return len;
30+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
题目描述:
2+
你有一个单词列表 words 和一个模式 pattern,你想知道 words 中的哪些单词与模式匹配。
3+
4+
如果存在字母的排列 p ,使得将模式中的每个字母 x 替换为 p(x) 之后,我们就得到了所需的单词,那么单词与模式是匹配的。
5+
6+
(回想一下,字母的排列是从字母到字母的双射:每个字母映射到另一个字母,没有两个字母映射到同一个字母。)
7+
8+
返回 words 中与给定模式匹配的单词列表。
9+
10+
你可以按任何顺序返回答案。
11+
12+
13+
14+
示例:
15+
16+
输入:words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
17+
输出:["mee","aqq"]
18+
解释:
19+
"mee" 与模式匹配,因为存在排列 {a -> m, b -> e, ...}。
20+
"ccc" 与模式不匹配,因为 {a -> c, b -> c, ...} 不是排列。
21+
因为 a 和 b 映射到同一个字母。
22+
23+
24+
提示:
25+
26+
1 <= words.length <= 50
27+
1 <= pattern.length = words[i].length <= 20
28+
29+
30+
31+
题解: TODO 8ms 待优化
32+
class Solution {
33+
public List<String> findAndReplacePattern(String[] words, String pattern) {
34+
35+
List<String> result = new ArrayList<>();
36+
37+
char[] patternChar = pattern.toCharArray();
38+
String regex = "";
39+
for(int i=0; i<patternChar.length; i++){
40+
regex += pattern.indexOf(patternChar[i]);
41+
}
42+
43+
for(int i=0; i<words.length; i++){
44+
if(words[i].length() != pattern.length()) continue;
45+
String temp = "";
46+
char[] wordChar = words[i].toCharArray();
47+
for(int j=0; j<wordChar.length; j++){
48+
temp += words[i].indexOf(wordChar[j]);
49+
}
50+
if(regex.equals(temp)){
51+
result.add(words[i]);
52+
}
53+
}
54+
55+
return result;
56+
}
57+
}

0 commit comments

Comments
 (0)