Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

字符串中不同整数的数目 #126

Open
yankewei opened this issue Mar 28, 2021 · 1 comment
Open

字符串中不同整数的数目 #126

yankewei opened this issue Mar 28, 2021 · 1 comment
Labels
简单 题目难度为简单

Comments

@yankewei
Copy link
Owner

给你一个字符串word,该字符串由数字和小写英文字母组成。

请你用空格替换每个不是数字的字符。例如,"a123bc34d8ef34" 将会变成 " 123 34 8 34" 。注意,剩下的这些整数间至少要用一个空格隔开:"123"、"34"、"8""34"

返回对 word 完成替换后形成的 不同 整数的数目。

如果两个整数的 不含前导零 的十进制表示不同,则认为这两个整数也不同。

示例 1:

输入:word = "a123bc34d8ef34"
输出:3
解释:不同的整数有 "123"、"34" 和 "8" 。注意,"34" 只计数一次。

示例 2:

输入:word = "leet1234code234"
输出:2

示例 3:

输入:word = "a1b01c001"
输出:1
解释:"1"、"01" 和 "001" 视为同一个整数的十进制表示,因为在比较十进制值时会忽略前导零的存在。

提示:

  • 1 <= word.length <= 1000
  • word 由数字和小写英文字母组成
@yankewei yankewei added the 简单 题目难度为简单 label Mar 28, 2021
@yankewei
Copy link
Owner Author

正则匹配即可,就是有一点要注意,尽量不用string转int这样的函数,因为如果字符串超过了int的最大范围,结果也是int的最大值,会造成即使字符串不同,转化后的结果可能会相同。

func numDifferentIntegers(word string) int {
    set := map[string]struct{}{}
    re := regexp.MustCompile(`[0-9]+`)
    strSlice := re.FindAllStringSubmatch(word, -1)
    for _, v := range strSlice {
	val := strings.TrimLeft(v[0], "0")
	if _, e := set[val]; !e {
	    set[val] = struct{}{}
	}
    }
    return len(set)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
简单 题目难度为简单
Projects
None yet
Development

No branches or pull requests

1 participant