![JAR search and dependency download from the Maven repository](/logo.png)
g2001_2100.s2014_longest_subsequence_repeated_k_times.Solution.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-kotlin Show documentation
Show all versions of leetcode-in-kotlin Show documentation
Kotlin-based LeetCode algorithm problem solutions, regularly updated
package g2001_2100.s2014_longest_subsequence_repeated_k_times
// #Hard #String #Greedy #Backtracking #Counting #Enumeration
// #2023_06_23_Time_333_ms_(100.00%)_Space_39_MB_(100.00%)
@Suppress("NAME_SHADOWING")
class Solution {
fun longestSubsequenceRepeatedK(s: String, k: Int): String {
val ca = s.toCharArray()
val freq = CharArray(26)
for (value in ca) {
++freq[value.code - 'a'.code]
}
val cand: Array?> = arrayOfNulls(8)
cand[1] = ArrayList()
var ans = ""
for (i in 0..25) {
if (freq[i].code >= k) {
ans = "" + ('a'.code + i).toChar()
cand[1]?.add(ans)
}
}
for (i in 2..7) {
cand[i] = ArrayList()
for (prev in cand[i - 1]!!) {
for (c in cand[1]!!) {
val next = prev + c
if (isSubsequenceRepeatedK(ca, next, k)) {
ans = next
cand[i]?.add(ans)
}
}
}
}
return ans
}
private fun isSubsequenceRepeatedK(ca: CharArray, t: String, k: Int): Boolean {
var k = k
val ta = t.toCharArray()
val n = ca.size
val m = ta.size
var i = 0
while (k-- > 0) {
var j = 0
while (i < n && j < m) {
if (ca[i] == ta[j]) {
j++
}
i++
}
if (j != m) {
return false
}
}
return true
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy