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 574c350

Browse files
🐱(hash): 409. 最长回文串
补充 golang 题解 + 二刷
1 parent 0ac2a23 commit 574c350

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

‎docs/data-structure/string/README.md‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1246,6 +1246,68 @@ class Solution(object):
12461246
return length + num
12471247
```
12481248

1249+
----
1250+
1251+
2020年03月19日 二刷
1252+
1253+
在最后返回时可以判断下结果长度和最初字符串的长度,如果结果长度短,则将结果长度 +1(即加上任何一个字符构成奇数回文串)。
1254+
1255+
<!-- tabs:start -->
1256+
1257+
#### **Python**
1258+
1259+
```python
1260+
class Solution:
1261+
def longestPalindrome(self, s: str) -> int:
1262+
length = len(s)
1263+
c_map = dict()
1264+
for c in s:
1265+
if c not in c_map:
1266+
c_map[c] = 0
1267+
c_map[c] += 1
1268+
res = 0
1269+
for v in c_map.values():
1270+
if v % 2 == 0:
1271+
# 偶数处理
1272+
res += v
1273+
else:
1274+
# 奇数处理
1275+
res += (v - 1)
1276+
return res + 1 if res < length else res
1277+
```
1278+
1279+
#### **Go**
1280+
1281+
```go
1282+
func longestPalindrome(s string) int {
1283+
res := 0
1284+
cMap := make(map[string]int)
1285+
// 数据统计
1286+
for _, c := range s {
1287+
if _, ok := cMap[string(c)]; !ok {
1288+
cMap[string(c)] = 0
1289+
}
1290+
cMap[string(c)] += 1
1291+
}
1292+
1293+
// 判断奇偶
1294+
for _, value := range cMap {
1295+
if value % 2 == 0 {
1296+
res += value
1297+
} else {
1298+
res += (value - 1)
1299+
}
1300+
}
1301+
1302+
if res < len(s) {
1303+
return res + 1
1304+
}
1305+
return res
1306+
}
1307+
```
1308+
1309+
<!-- tabs:end -->
1310+
12491311

12501312
## 459. 重复的子字符串
12511313

0 commit comments

Comments
(0)

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