3. Longest Substring Without Repeating Characters

题目

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.

解题思路:
这道题求解的是最大子串的长度

  1. 寻找一种容器,可以用来容纳字符串,
  2. 字符串容器能够判断一个字符是否存在于容器中
  3. 若是字符串已经存在于容器中,相对应的最大子串的长度和最大子串都应作出相应的处理

解题代码:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int characters[256] = {0};//保存出现的字符串
    int max_length = 0; // 最大子字符串长度
    int index_substring = 0;//最大子字符串的起始索引
    
    for(int i = 0; i < s.size(); i++){
        if (characters[s[i]] == 0 || characters[s[i]] < index_substring ) {
            
            //characters[s[i]] == 0 说明该字符还不存在
            //characters[s[i]] < index_substring 说明该字符已经出现过,但是不在现在的最大子字符串里面,比如 "tmmzuxt" 中的最大子字符串是 "mzuxt" ,但是 "mzuxt" 中的 t 在第一个就出现过了,但是 t 在当前的最大子字符串 “mzuxt” 没有出现过,所以也需要计数,加入最大子字符串长度
            max_length = max(max_length, i - index_substring + 1);
        }else{
            //该字符已经存在了,那么将更新 index_substring
            index_substring = characters[s[i]];
        }
        //给 characters[s[i]]  赋值 i+1 是为了作为最大子字符串的起始索引
        characters[s[i]] = i + 1;
    }
    return max_length;
        
    }
};

参考

  1. https://leetcode.com/problems/longest-substring-without-repeating-characters/solution/
  2. http://www.cnblogs.com/grandyang/p/4480780.html

你可能感兴趣的:(3. Longest Substring Without Repeating Characters)