wide/util/string.go

62 lines
1.4 KiB
Go
Executable File

// Copyright (c) 2015, B3log
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package util
type str struct{}
// String utilities.
var Str = str{}
// Contains determines whether the str is in the strs.
func (*str) Contains(str string, strs []string) bool {
for _, v := range strs {
if v == str {
return true
}
}
return false
}
// LCS gets the longest common substring of s1 and s2.
//
// Refers to http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring.
func (*str) LCS(s1 string, s2 string) string {
var m = make([][]int, 1+len(s1))
for i := 0; i < len(m); i++ {
m[i] = make([]int, 1+len(s2))
}
longest := 0
xLongest := 0
for x := 1; x < 1+len(s1); x++ {
for y := 1; y < 1+len(s2); y++ {
if s1[x-1] == s2[y-1] {
m[x][y] = m[x-1][y-1] + 1
if m[x][y] > longest {
longest = m[x][y]
xLongest = x
}
} else {
m[x][y] = 0
}
}
}
return s1[xLongest-longest : xLongest]
}