Movatterモバイル変換


[0]ホーム

URL:


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

Commitf3e4c67

Browse files
authored
Create 1048-longest-string-chain.kt
1 parent7465de5 commitf3e4c67

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

‎kotlin/1048-longest-string-chain.kt

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
//dfs
2+
classSolution {
3+
funlongestStrChain(words:Array<String>):Int {
4+
val wordList= words.toHashSet()
5+
val dp=HashMap<String,Int>()
6+
7+
fundfs(word:String,len:Int):Int {
8+
if (word!in wordList)return0
9+
if ("$word:$len"in dp)return dp["$word:$len"]!!
10+
11+
var res= len
12+
for (iin0 until26) {
13+
for (jin0..word.length) {
14+
val nextWord= word.substring(0, j)+ ('a'+ i)+ word.substring(j, word.length)
15+
res= maxOf(res, dfs(nextWord, len+1))
16+
}
17+
}
18+
19+
dp["$word:$len"]= res
20+
return res
21+
}
22+
23+
var res=1
24+
for (wordin wordList) {
25+
res= maxOf(res, dfs(word,1))
26+
}
27+
28+
return res
29+
}
30+
}
31+
32+
//dp
33+
classSolution {
34+
funlongestStrChain(words:Array<String>):Int {
35+
words.sortBy { it.length }
36+
val dp=HashMap<String,Int>()
37+
38+
var res=0
39+
for (wordin words) {
40+
var cur=1
41+
for (iin0 until word.length) {
42+
val nextWord= word.substring(0, i)+ word.substring(i+1)
43+
dp[nextWord]?.let {
44+
cur= maxOf(cur, it+1)
45+
}
46+
}
47+
48+
dp[word]= cur
49+
res= maxOf(res, cur)
50+
}
51+
52+
return res
53+
}
54+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp