Skip to content

Commit 2336ef6

Browse files
authored
Merge pull request ByteByteGoHq#2 from Destiny-02/main
Add Next Lexicographical Sequence
2 parents 56dfc02 + 35d71c1 commit 2336ef6

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package common.twopointers.nextlexicographicalsequence
2+
3+
class NextLexicographicalSequence {
4+
5+
fun solution(s: String): String {
6+
val letters = s.toCharArray()
7+
8+
// Locate the pivot, which is the first character from the right that breaks
9+
// non-increasing order. Start searching from the second-to-last position,
10+
// since the last character is neither increasing nor decreasing.
11+
var pivot = letters.size - 2
12+
while (pivot >= 0 && letters[pivot] >= letters[pivot + 1]) {
13+
pivot--
14+
}
15+
16+
// If pivot is not found, the string is already in its largest permutation. In
17+
// this case, reverse the string to obtain the smallest permutation.
18+
if (pivot == -1) {
19+
letters.reverse()
20+
return letters.joinToString("")
21+
}
22+
23+
// Find the rightmost successor to the pivot.
24+
var rightmostSuccessor = letters.size - 1
25+
while (letters[rightmostSuccessor] <= letters[pivot]) {
26+
rightmostSuccessor--
27+
}
28+
29+
// Swap the rightmost successor with the pivot to increase the lexicographical
30+
// order of the suffix.
31+
letters[pivot] = letters[rightmostSuccessor].also { letters[rightmostSuccessor] = letters[pivot] }
32+
33+
// Reverse the suffix after the pivot to minimize its permutation.
34+
val suffix = letters.sliceArray(pivot + 1 until letters.size)
35+
suffix.reverse()
36+
37+
return (letters.sliceArray(0..pivot) + suffix).joinToString("")
38+
}
39+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package common.twopointers.nextlexicographicalsequence
2+
3+
import org.junit.jupiter.api.Test
4+
import kotlin.test.assertEquals
5+
6+
class NextLexicographicalSequenceTest {
7+
8+
private val question = NextLexicographicalSequence()
9+
10+
@Test
11+
fun `Verify solution`() {
12+
assertEquals("a", question.solution("a"))
13+
assertEquals("aaaa", question.solution("aaaa"))
14+
assertEquals("ynsdeit", question.solution("ynitsed"))
15+
assertEquals("nuash", question.solution("nuahs"))
16+
assertEquals("abdc", question.solution("abcd"))
17+
assertEquals("abcd", question.solution("dcba"))
18+
}
19+
}

0 commit comments

Comments
 (0)