Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0861f89

Browse files
committed
solve 438.找到字符串中所有字母异位词
1 parent 430c9cf commit 0861f89

File tree

1 file changed

+101
-0
lines changed

1 file changed

+101
-0
lines changed
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
/*
2+
* @lc app=leetcode.cn id=438 lang=java
3+
*
4+
* [438] 找到字符串中所有字母异位词
5+
*
6+
* https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/description/
7+
*
8+
* algorithms
9+
* Medium (44.04%)
10+
* Likes: 309
11+
* Dislikes: 0
12+
* Total Accepted: 30.9K
13+
* Total Submissions: 68.5K
14+
* Testcase Example: '"cbaebabacd"\n"abc"'
15+
*
16+
* 给定一个字符串 s 和一个非空字符串 p,找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引。
17+
*
18+
* 字符串只包含小写英文字母,并且字符串 s 和 p 的长度都不超过 20100。
19+
*
20+
* 说明:
21+
*
22+
*
23+
* 字母异位词指字母相同,但排列不同的字符串。
24+
* 不考虑答案输出的顺序。
25+
*
26+
*
27+
* 示例 1:
28+
*
29+
*
30+
* 输入:
31+
* s: "cbaebabacd" p: "abc"
32+
*
33+
* 输出:
34+
* [0, 6]
35+
*
36+
* 解释:
37+
* 起始索引等于 0 的子串是 "cba", 它是 "abc" 的字母异位词。
38+
* 起始索引等于 6 的子串是 "bac", 它是 "abc" 的字母异位词。
39+
*
40+
*
41+
* 示例 2:
42+
*
43+
*
44+
* 输入:
45+
* s: "abab" p: "ab"
46+
*
47+
* 输出:
48+
* [0, 1, 2]
49+
*
50+
* 解释:
51+
* 起始索引等于 0 的子串是 "ab", 它是 "ab" 的字母异位词。
52+
* 起始索引等于 1 的子串是 "ba", 它是 "ab" 的字母异位词。
53+
* 起始索引等于 2 的子串是 "ab", 它是 "ab" 的字母异位词。
54+
*
55+
*
56+
*/
57+
58+
// @lc code=start
59+
class Solution {
60+
public List<Integer> findAnagrams(String s, String p) {
61+
int[] need = new int[128];
62+
int[] window = new int[128];
63+
for (char ch : p.toCharArray()) {
64+
need[ch]++;
65+
}
66+
67+
List<Integer> result = new ArrayList<>();
68+
int left = 0, right = 0;
69+
int count = 0;
70+
71+
while (right < s.length()) {
72+
char ch = s.charAt(right);
73+
right++;
74+
if (need[ch] > 0) {
75+
window[ch]++;
76+
if (window[ch] <= need[ch]) {
77+
count++;
78+
}
79+
}
80+
81+
while (right - left >= p.length()) {
82+
if (count == p.length()) {
83+
result.add(left);
84+
}
85+
86+
ch = s.charAt(left);
87+
left++;
88+
if (need[ch] > 0) {
89+
if (window[ch] <= need[ch]) {
90+
count--;
91+
}
92+
window[ch]--;
93+
}
94+
}
95+
}
96+
97+
return result;
98+
}
99+
}
100+
// @lc code=end
101+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /