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

5543. 两个相同字符之间的最长子字符串(第 211 场周赛) #65

Open
yankewei opened this issue Oct 18, 2020 · 1 comment
Open
Labels
哈希表 题目包含哈希表解法 字符串 题目类型为字符串 简单 题目难度为简单

Comments

@yankewei
Copy link
Owner

给你一个字符串 s,请你返回 两个相同字符之间的最长子字符串的长度 ,计算长度时不含这两个字符。如果不存在这样的子字符串,返回 -1 。

子字符串 是字符串中的一个连续字符序列。

示例 1:

输入:s = "aa"
输出:0
解释:最优的子字符串是两个 'a' 之间的空子字符串。

示例 2:

输入:s = "abca"
输出:2
解释:最优的子字符串是 "bc" 。

示例 3:

输入:s = "cbzxy"
输出:-1
解释:s 中不存在出现出现两次的字符,所以返回 -1 。

示例 4:

输入:s = "cabbac"
输出:4
解释:最优的子字符串是 "abba" ,其他的非最优解包括 "bb" 和 "" 。

提示:

  • 1 <= s.length <= 300
  • s 只含小写英文字母

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/largest-substring-between-two-equal-characters

@yankewei yankewei added 哈希表 题目包含哈希表解法 简单 题目难度为简单 labels Oct 18, 2020
@yankewei
Copy link
Owner Author

哈希表

只要记录字符出现的第一个和最后一次出现的位置即可。

func maxLengthBetweenEqualCharacters(s string) int {
    ret := -1
    m := map[byte][2]int{}
    for i := 0; i < len(s); i++ {
	value, exist := m[s[i]]
	if exist {
	    value[1] = i
	} else {
	    value[0] = i
	}
	m[s[i]] = value
    }
    if len(m) == 0 {
	return -1
    }
    for _, v := range m {
	if v[1]-v[0] > ret {
	    ret = v[1] - v[0]
	}
    }
    return ret - 1
}

@yankewei yankewei added the 字符串 题目类型为字符串 label Oct 18, 2020
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