首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 互联网 >

Longest Substring Without Repeating Characters -LeetCode OJ

2013-10-02 
Longest Substring Without Repeating Characters ---LeetCode OJ题目描述:Given a string, find the leng

Longest Substring Without Repeating Characters ---LeetCode OJ

题目描述:

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

思路:用hashtable来标记每个字符出现的位置

代码:

class Solution {public:    int lengthOfLongestSubstring(string s) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(s.size() == 0) return 0;        int cnt=0;        int hash[256];        int maxlen=-1;        memset(hash,-1,sizeof(hash));                for(int i=0; i<s.size(); i++)        {            char ch = s[i];            if(hash[ch] == -1)            {                cnt++;                hash[ch] = i;                maxlen = max(maxlen,cnt);            }            else             {               int index = hash[ch];               //cnt = i-index;               for(int j=i-cnt; j<=index; j++)               {                   hash[s[j]] = -1;               }               cnt = i-index;               hash[ch]=i;               maxlen = max(maxlen,cnt);            }        }        return maxlen;    }};


热点排行