Skip to content

Commit b17b2f4

Browse files
committed
feat: add python and java solutions to lcof question
添加《剑指 Offer》题解:面试题38. 字符串的排列
1 parent e49b738 commit b17b2f4

File tree

3 files changed

+102
-2
lines changed

3 files changed

+102
-2
lines changed

lcof/面试题38. 字符串的排列/README.md

+51-2
Original file line numberDiff line numberDiff line change
@@ -25,14 +25,63 @@
2525
<!-- 这里可写当前语言的特殊实现逻辑 -->
2626

2727
```python
28-
28+
class Solution:
29+
def permutation(self, s: str) -> List[str]:
30+
def dfs(x):
31+
if x == len(s) - 1:
32+
res.append("".join(chars))
33+
return
34+
t = set()
35+
for i in range(x, len(s)):
36+
if chars[i] in t:
37+
continue
38+
t.add(chars[i])
39+
chars[i], chars[x] = chars[x], chars[i]
40+
dfs(x + 1)
41+
chars[i], chars[x] = chars[x], chars[i]
42+
chars, res = list(s), []
43+
dfs(0)
44+
return res
2945
```
3046

3147
### Java
3248
<!-- 这里可写当前语言的特殊实现逻辑 -->
3349

3450
```java
35-
51+
class Solution {
52+
private char[] chars;
53+
private List<String> res;
54+
55+
public String[] permutation(String s) {
56+
chars = s.toCharArray();
57+
res = new ArrayList<>();
58+
dfs(0);
59+
return res.toArray(new String[res.size()]);
60+
}
61+
62+
private void dfs(int x) {
63+
if (x == chars.length - 1) {
64+
res.add(String.valueOf(chars));
65+
return;
66+
}
67+
Set<Character> set = new HashSet<>();
68+
for (int i = x; i < chars.length; ++i) {
69+
if (set.contains(chars[i])) {
70+
continue;
71+
}
72+
set.add(chars[i]);
73+
swap(i, x);
74+
dfs(x + 1);
75+
swap(i, x);
76+
}
77+
}
78+
79+
private void swap(int i, int j) {
80+
char t = chars[i];
81+
chars[i] = chars[j];
82+
chars[j] = t;
83+
}
84+
}
3685
```
3786

3887
### ...
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
private char[] chars;
3+
private List<String> res;
4+
5+
public String[] permutation(String s) {
6+
chars = s.toCharArray();
7+
res = new ArrayList<>();
8+
dfs(0);
9+
return res.toArray(new String[res.size()]);
10+
}
11+
12+
private void dfs(int x) {
13+
if (x == chars.length - 1) {
14+
res.add(String.valueOf(chars));
15+
return;
16+
}
17+
Set<Character> set = new HashSet<>();
18+
for (int i = x; i < chars.length; ++i) {
19+
if (set.contains(chars[i])) {
20+
continue;
21+
}
22+
set.add(chars[i]);
23+
swap(i, x);
24+
dfs(x + 1);
25+
swap(i, x);
26+
}
27+
}
28+
29+
private void swap(int i, int j) {
30+
char t = chars[i];
31+
chars[i] = chars[j];
32+
chars[j] = t;
33+
}
34+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution:
2+
def permutation(self, s: str) -> List[str]:
3+
def dfs(x):
4+
if x == len(s) - 1:
5+
res.append("".join(chars))
6+
return
7+
t = set()
8+
for i in range(x, len(s)):
9+
if chars[i] in t:
10+
continue
11+
t.add(chars[i])
12+
chars[i], chars[x] = chars[x], chars[i]
13+
dfs(x + 1)
14+
chars[i], chars[x] = chars[x], chars[i]
15+
chars, res = list(s), []
16+
dfs(0)
17+
return res

0 commit comments

Comments
 (0)