LeetCode 3. Longest Substring Without Repeating Characters

来源:互联网 发布:matlab 矩阵赋值 编辑:程序博客网 时间:2024/05/20 22:35

3. Longest Substring Without Repeating Characters

Description
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.

Analysis
这道题的意思是返回所给字符串中最长的没有重复字符的子字符串的长度。
我的做法是利用两个整数i,j来表示子字符串在字符串中的开始下标与结束下标。
同时利用一个bool数组来判断是否当前字符出现过。即flag。
初始化为false,当出现过在子字符串中时更新为true。
当当前字符串已经在子字符串出现过的时候,就会发现表示该字符是够出现的数组为显示的true。
所以此时要更新子字符开始的下标,更新到当前字符曾经在子字符串中出现的位置的下一个。

Code

class Solution {public:    int lengthOfLongestSubstring(string s) {        int res =0 ;        int i =0 ;        int j =0 ;        bool arr[128] = {false};        int len = s.size();        while(j<len){            if(arr[s[j]]){                res = max(res,j-i);                while(s[i] != s[j]){                    arr[s[i]] = 0;                    i++;                }                i++;                j++;            }            else{                arr[s[j]] = 1;                j++;            }        }        res = max (res,len-i);        return res;    }};
阅读全文
0 0