算法题——Longest Substring Without Repeating Characters(C++)hash思想

题目描述:
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given “abcabcbb”, the answer is “abc”, which the length is 3.
Given “bbbbb”, the answer is “b”, with the length of 1.
Given “pwwkew”, 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.

读题:
找最长的不包含重复字符的子字符串

知识储备:
ASCII码
ASCII码占用一个字节,可以有0~255共256个取值。前128个为常用的字符如运算符,字母 ,数字等 键盘上可以显示的后 128个为 特殊字符是键盘上找不到的字符。

Hash:映射
使用Hash思想题目的特点
1、输入的数据的变化范围是有限的;
2、能够得到对应关系

解题思路:
要找字符串,而不是单纯地去掉重复字符,因此只用map或set类型重新输入一次数据是不够的。

当出现了一个重复字符时,前面原有的字符串已经不能继续和后面的字符串组成子字符串,这时候要统计新的子字符串,要从重复字符上一次出现位置的下一位开始记录。

要统计这些字符是否已经出现过,使用一个数组,借助hash思想,每一个字符对应数组的一个项。因为ASCII码共有256个取值,因此使用当前字符的ASCII码减去最小的字符即空格的ASCII码。获取hash后对应的值。

在初始化数组的时候,想要将所有项初始化为-1,数组不允许直接复制和赋值,记得有个函数memset,在使用中发现,menset对int型数组不起作用,而对char类型数组是可以的。
原来是因为字符型占据内存大小是1Byte,而memset函数也是以字节为单位进行赋值。而对于整型的,使用memset还是按字节赋值,这样赋值完以后,每个数组元素的值实际上是0x01010101即十进制的 16843009。

提交代码:

#include<vector>
using namespace std;
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if (s.length() < 2) {
            return s.length();
        }
        int mark[256]= {0};
        for (int j = 0; j < 256; j++) {
            mark[j] = -1;
        }
        int len = 1, start = -1;
        for (int i = 0; i < s.length(); i++) {
            if (mark[s[i]-' '] > start)
                start = mark[s[i]-' '];
            mark[s[i]-' '] = i;
            len = max(len, i - start);
        }
        return  len;
    }
};
点赞