题解 | #在字符串中找出连续最长的数字串#
在字符串中找出连续最长的数字串
https://www.nowcoder.com/practice/2c81f88ecd5a4cc395b5308a99afbbec
package main import ( "fmt" ) func isDigit(ch byte) bool { return '0' <= ch && ch <= '9' } func findLongestDigitSubString(s string) []string { var ans []string var maxLength int left, right := 0, 0 for right < len(s) { if !isDigit(s[right]) { right++ continue } left = right for right < len(s) && isDigit(s[right]) {right++} substr := s[left:right] if len(substr) == maxLength { ans = append(ans, substr) } else if len(substr) > maxLength { // fmt.Println("=======") maxLength = len(substr) ans = []string{substr} } } return ans } func main() { for { var s string n, _ := fmt.Scan(&s) if n == 0 { break } ans := findLongestDigitSubString(s) if len(ans) == 1 { fmt.Printf("%s,%d\n", ans[0], len(ans[0])) } else { var t string for _, one := range ans { t += fmt.Sprintf("%s", one) } fmt.Printf("%s,%d", t, len(ans[0])) } } }
// 本题输入多行字符串,所以采用:fmt.Scan(&s)