Last active
August 25, 2023 22:20
-
-
Save benmoss/3509a7f47a647c52c0034ed6959b514c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package leetcode | |
import ( | |
"testing" | |
"github.com/stretchr/testify/assert" | |
) | |
func highlight(text string, highlights []string) string { | |
var result string | |
var isBold bool | |
lastBold := -1 | |
for i := 0; i < len(text); i++ { | |
for _, highlight := range highlights { | |
if i+len(highlight) > len(text) { | |
continue | |
} | |
if text[i:i+len(highlight)] == highlight { | |
if !isBold { | |
isBold = true | |
result += "<b>" | |
} | |
lastBold = max(lastBold, i+len(highlight)) | |
} | |
} | |
if isBold && i == lastBold { | |
result += "</b>" | |
isBold = false | |
} | |
result += string(text[i]) | |
} | |
if isBold { | |
result += "</b>" | |
} | |
return result | |
} | |
func Test_highlight(t *testing.T) { | |
type args struct { | |
text string | |
highlights []string | |
} | |
tests := []struct { | |
name string | |
args args | |
want string | |
}{ | |
{ | |
name: "", | |
args: args{ | |
text: "abc123", | |
highlights: []string{"ab", "a", "b"}, | |
}, | |
want: "<b>ab</b>c123", | |
}, | |
{ | |
name: "", | |
args: args{ | |
text: "abcxyz123", | |
highlights: []string{"abc", "123"}, | |
}, | |
want: "<b>abc</b>xyz<b>123</b>", | |
}, | |
{ | |
name: "", | |
args: args{ | |
text: "aaabbcc", | |
highlights: []string{"aaa", "aab", "bc"}, | |
}, | |
want: "<b>aaabbc</b>c", | |
}, | |
} | |
for _, tt := range tests { | |
t.Run(tt.name, func(t *testing.T) { | |
assert.Equal(t, tt.want, highlight(tt.args.text, tt.args.highlights)) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment