Skip to content

Commit f935e83

Browse files
author
openset
committed
Add: Last Substring in Lexicographical Order
1 parent f0d1f8e commit f935e83

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package problem_1163
2+
3+
func lastSubstring(s string) string {
4+
last, n := 0, len(s)
5+
for i := 1; i < n; i++ {
6+
if s[i-1] == s[i] {
7+
// all of s[last:i+1] are the same letter.
8+
// 'i' has no chance to be the new 'last'
9+
// the reason is
10+
// 1. s[i+1] > s[i], 'i+1' is the new 'last'
11+
// 2. s[i+1] < s[i], 'last' is still 'last'
12+
// 3. s[i+1] = s[i], 'i+1' is the new 'i'
13+
// like above, need a different letter to make decision
14+
continue
15+
}
16+
for l := 0; i+l < n; l++ {
17+
if s[last+l] < s[i+l] {
18+
// s[i:] is bigger than s[last:]
19+
// new begin is here
20+
last = i
21+
break
22+
}
23+
if s[last+l] > s[i+l] {
24+
// s[last:] is bigger than s[i:]
25+
// no need to compare continue
26+
break
27+
}
28+
}
29+
}
30+
return s[last:]
31+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package problem_1163
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input string
7+
expected string
8+
}
9+
10+
func TestLastSubstring(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: "abab",
14+
expected: "bab",
15+
},
16+
{
17+
input: "abcdabc",
18+
expected: "dabc",
19+
},
20+
{
21+
input: "ffbcdfeda",
22+
expected: "ffbcdfeda",
23+
},
24+
{
25+
input: "hksljkjsfjv",
26+
expected: "v",
27+
},
28+
}
29+
for _, tc := range tests {
30+
output := lastSubstring(tc.input)
31+
if output != tc.expected {
32+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
33+
}
34+
}
35+
}

0 commit comments

Comments
 (0)