
题目描述
给出长度相同的两个字符串s1
和 s2
,还有一个字符串 baseStr
。
其中 s1[i]
和 s2[i]
是一组等价字符。
- 举个例子,如果
s1 = "abc"
且 s2 = "cde"
,那么就有 'a' == 'c', 'b' == 'd', 'c' == 'e'
。
等价字符遵循任何等价关系的一般规则:
- 自反性 :
'a' == 'a'
- 对称性 :
'a' == 'b'
则必定有 'b' == 'a'
- 传递性 :
'a' == 'b'
且 'b' == 'c'
就表明 'a' == 'c'
例如, s1 = "abc"
和 s2 = "cde"
的等价信息和之前的例子一样,那么 baseStr = "eed"
, "acd"
或 "aab"
,这三个字符串都是等价的,而 "aab"
是 baseStr
的按字典序最小的等价字符串
利用 s1
和 s2
的等价信息,找出并返回 baseStr
的按字典序排列最小的等价字符串。
示例 1:
输入:s1 = "parker", s2 = "morris", baseStr = "parser"
输出:"makkek"
解释:根据 A 和 B 中的等价信息,我们可以将这些字符分为 [m,p], [a,o], [k,r,s], [e,i] 共 4 组。每组中的字符都是等价的,并按字典序排列。所以答案是 "makkek"。
示例 2:
输入:s1 = "hello", s2 = "world", baseStr = "hold"
输出:"hdld"
解释:根据 A 和 B 中的等价信息,我们可以将这些字符分为 [h,w], [d,e,o], [l,r] 共 3 组。所以只有 S 中的第二个字符 'o' 变成 'd',最后答案为 "hdld"。
示例 3:
输入:s1 = "leetcode", s2 = "programs", baseStr = "sourcecode"
输出:"aauaaaaada"
解释:我们可以把 A 和 B 中的等价字符分为 [a,o,e,r,s,c], [l,p], [g,t] 和 [d,m] 共 4 组,因此 S 中除了 'u' 和 'd' 之外的所有字母都转化成了 'a',最后答案为 "aauaaaaada"。
提示:
1 <= s1.length, s2.length, baseStr <= 1000
s1.length == s2.length
- 字符串
s1
, s2
, and baseStr
仅由从 'a'
到 'z'
的小写英文字母组成。
解法
方法一:并查集
我们可以使用并查集来处理等价字符的关系。每个字符可以看作一个节点,等价关系可以看作是连接这些节点的边。通过并查集,我们可以将所有等价的字符归为一类,并且在查询时能够快速找到每个字符的代表元素。我们在进行合并操作时,始终将代表元素设置为字典序最小的字符,这样可以确保最终得到的字符串是按字典序排列的最小等价字符串。
时间复杂度 \(O((n + m) \times \log |\Sigma|)\),空间复杂度 \(O(|\Sigma|)\)。其中 \(n\) 是字符串 \(s1\) 和 \(s2\) 的长度,而 \(m\) 是字符串 \(baseStr\) 的长度,而 \(|\Sigma|\) 是字符集的大小,本题中 \(|\Sigma| = 26\)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | class Solution:
def smallestEquivalentString(self, s1: str, s2: str, baseStr: str) -> str:
def find(x: int) -> int:
if p[x] != x:
p[x] = find(p[x])
return p[x]
p = list(range(26))
for a, b in zip(s1, s2):
x, y = ord(a) - ord("a"), ord(b) - ord("a")
px, py = find(x), find(y)
if px < py:
p[py] = px
else:
p[px] = py
return "".join(chr(find(ord(c) - ord("a")) + ord("a")) for c in baseStr)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31 | class Solution {
private final int[] p = new int[26];
public String smallestEquivalentString(String s1, String s2, String baseStr) {
for (int i = 0; i < p.length; ++i) {
p[i] = i;
}
for (int i = 0; i < s1.length(); ++i) {
int x = s1.charAt(i) - 'a';
int y = s2.charAt(i) - 'a';
int px = find(x), py = find(y);
if (px < py) {
p[py] = px;
} else {
p[px] = py;
}
}
char[] s = baseStr.toCharArray();
for (int i = 0; i < s.length; ++i) {
s[i] = (char) ('a' + find(s[i] - 'a'));
}
return String.valueOf(s);
}
private int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 | class Solution {
public:
string smallestEquivalentString(string s1, string s2, string baseStr) {
vector<int> p(26);
iota(p.begin(), p.end(), 0);
auto find = [&](this auto&& find, int x) -> int {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
};
for (int i = 0; i < s1.length(); ++i) {
int x = s1[i] - 'a';
int y = s2[i] - 'a';
int px = find(x), py = find(y);
if (px < py) {
p[py] = px;
} else {
p[px] = py;
}
}
string s;
for (char c : baseStr) {
s.push_back('a' + find(c - 'a'));
}
return s;
}
};
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 | func smallestEquivalentString(s1 string, s2 string, baseStr string) string {
p := make([]int, 26)
for i := 0; i < 26; i++ {
p[i] = i
}
var find func(int) int
find = func(x int) int {
if p[x] != x {
p[x] = find(p[x])
}
return p[x]
}
for i := 0; i < len(s1); i++ {
x := int(s1[i] - 'a')
y := int(s2[i] - 'a')
px := find(x)
py := find(y)
if px < py {
p[py] = px
} else {
p[px] = py
}
}
var s []byte
for i := 0; i < len(baseStr); i++ {
s = append(s, byte('a'+find(int(baseStr[i]-'a'))))
}
return string(s)
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 | function smallestEquivalentString(s1: string, s2: string, baseStr: string): string {
const p: number[] = Array.from({ length: 26 }, (_, i) => i);
const find = (x: number): number => {
if (p[x] !== x) {
p[x] = find(p[x]);
}
return p[x];
};
for (let i = 0; i < s1.length; i++) {
const x = s1.charCodeAt(i) - 'a'.charCodeAt(0);
const y = s2.charCodeAt(i) - 'a'.charCodeAt(0);
const px = find(x);
const py = find(y);
if (px < py) {
p[py] = px;
} else {
p[px] = py;
}
}
const s: string[] = [];
for (let i = 0; i < baseStr.length; i++) {
const c = baseStr.charCodeAt(i) - 'a'.charCodeAt(0);
s.push(String.fromCharCode('a'.charCodeAt(0) + find(c)));
}
return s.join('');
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 | impl Solution {
pub fn smallest_equivalent_string(s1: String, s2: String, base_str: String) -> String {
fn find(x: usize, p: &mut Vec<usize>) -> usize {
if p[x] != x {
p[x] = find(p[x], p);
}
p[x]
}
let mut p = (0..26).collect::<Vec<_>>();
for (a, b) in s1.bytes().zip(s2.bytes()) {
let x = (a - b'a') as usize;
let y = (b - b'a') as usize;
let px = find(x, &mut p);
let py = find(y, &mut p);
if px < py {
p[py] = px;
} else {
p[px] = py;
}
}
base_str
.bytes()
.map(|c| (b'a' + find((c - b'a') as usize, &mut p) as u8) as char)
.collect()
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35 | public class Solution {
public string SmallestEquivalentString(string s1, string s2, string baseStr) {
int[] p = new int[26];
for (int i = 0; i < 26; i++) {
p[i] = i;
}
int Find(int x) {
if (p[x] != x) {
p[x] = Find(p[x]);
}
return p[x];
}
for (int i = 0; i < s1.Length; i++) {
int x = s1[i] - 'a';
int y = s2[i] - 'a';
int px = Find(x);
int py = Find(y);
if (px < py) {
p[py] = px;
} else {
p[px] = py;
}
}
var res = new System.Text.StringBuilder();
foreach (char c in baseStr) {
int idx = Find(c - 'a');
res.Append((char)(idx + 'a'));
}
return res.ToString();
}
}
|