LeetCode OJ 03 Longest Substring Without Repeating Characters

来源:互联网 发布:java统计在线人数 编辑:程序博客网 时间:2024/06/17 20:47

题目: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.

难度: medium

思路:

设置一个数组用来标记每个字符出现的位置,注意该数组存储的为ASCII码前128个常用字符

代码:

class Solution {public:    int lengthOfLongestSubstring(string s) {if(s.empty()) return 0;int size=s.size();int pos[128];memset(pos,-1,128*sizeof(int));int max=0;int offset=0;//offset marks the new start of the substringfor(int i=0;i<size;i++){char ch = s[i];if(pos[ch]<offset)//s[i]doesn't exist in substring{pos[ch]=i;max = i+1-offset>max? i+1-offset:max;}else{offset = pos[ch] +1 ;pos[ch] = i;}}return max;    }};


0 0
原创粉丝点击