题目:
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
题目翻译:
查找一个字符串中,最长不含有重复字母的字符串长度
题目思路:
创建一个字典,和一个起始标志。字典用于存储字母出现的位置,在我们遍历字符串的时候,如果在字母在字典中存储的位置小于起始标志,则认为从起始处开始,未出现重复字幕;否则认为出现重复情况,这个时候移动起始标志到当前位置,然后从起始位置处,继续开始遍历。我们遍历的位置,与起始标志的位置距离,就是不包含重复字符的字符串长度,在遍历过程中,找到最大值即可,注意边界条件。
代码:
use std::cmp;
fn length_of_longest_substring(s: String) -> i32 {
let mut ret: i32 = 0;
let mut start: i32 = -1;
let mut dic = vec![-1; 128];
let b = s.as_bytes();
for i in (0..s.len()) {
// if repeat just move the start
if (dic[b[i as usize] as usize] > start) {
start = dic[b[i as usize] as usize]
}
ret = std::cmp::max(ret, i as i32 - start);
dic[b[i as usize] as usize] = i as i32;
}
return ret as i32;
}
#[test]
fn test_length_of_longest_substring() {
let case1 = String::from("abcabcbb");
let case2 = String::from("bbbbb");
let case3 = String::from("pwwkew");
assert_eq!(length_of_longest_substring(case1), 3);
assert_eq!(length_of_longest_substring(case2), 1);
assert_eq!(length_of_longest_substring(case3), 3);
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。