comments | difficulty | edit_url | rating | source | tags | ||
---|---|---|---|---|---|---|---|
true |
简单 |
1281 |
第 211 场周赛 Q1 |
|
给你一个字符串 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
只含小写英文字母
用数组或哈希表记录字符串
遍历字符串
时间复杂度
class Solution:
def maxLengthBetweenEqualCharacters(self, s: str) -> int:
d = {}
ans = -1
for i, c in enumerate(s):
if c in d:
ans = max(ans, i - d[c] - 1)
else:
d[c] = i
return ans
class Solution {
public int maxLengthBetweenEqualCharacters(String s) {
int[] d = new int[26];
Arrays.fill(d, -1);
int ans = -1;
for (int i = 0; i < s.length(); ++i) {
int j = s.charAt(i) - 'a';
if (d[j] == -1) {
d[j] = i;
} else {
ans = Math.max(ans, i - d[j] - 1);
}
}
return ans;
}
}
class Solution {
public:
int maxLengthBetweenEqualCharacters(string s) {
vector<int> d(26, -1);
int ans = -1;
for (int i = 0; i < s.size(); ++i) {
int j = s[i] - 'a';
if (d[j] == -1) {
d[j] = i;
} else {
ans = max(ans, i - d[j] - 1);
}
}
return ans;
}
};
func maxLengthBetweenEqualCharacters(s string) int {
d := make([]int, 26)
for i := range d {
d[i] = -1
}
ans := -1
for i, c := range s {
c -= 'a'
if d[c] == -1 {
d[c] = i
} else {
ans = max(ans, i-d[c]-1)
}
}
return ans
}
function maxLengthBetweenEqualCharacters(s: string): number {
const n = s.length;
const pos = new Array(26).fill(-1);
let res = -1;
for (let i = 0; i < n; i++) {
const j = s[i].charCodeAt(0) - 'a'.charCodeAt(0);
if (pos[j] === -1) {
pos[j] = i;
} else {
res = Math.max(res, i - pos[j] - 1);
}
}
return res;
}
impl Solution {
pub fn max_length_between_equal_characters(s: String) -> i32 {
let s = s.as_bytes();
let n = s.len();
let mut pos = [-1; 26];
let mut res = -1;
for i in 0..n {
let j = (s[i] - b'a') as usize;
let i = i as i32;
if pos[j] == -1 {
pos[j] = i;
} else {
res = res.max(i - pos[j] - 1);
}
}
res
}
}
#define max(a, b) (((a) > (b)) ? (a) : (b))
int maxLengthBetweenEqualCharacters(char* s) {
int pos[26];
memset(pos, -1, sizeof(pos));
int n = strlen(s);
int res = -1;
for (int i = 0; i < n; i++) {
char c = s[i];
int j = c - 'a';
if (pos[j] == -1) {
pos[j] = i;
} else {
res = max(res, i - pos[j] - 1);
}
}
return res;
}