标签:leetcode longest substring wi
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.
class Solution { public: int lengthOfLongestSubstring(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function int max = 0; // 记录子串起始位置的前一个位置的下标 // 初始化为-1 int idx = -1; // 记录字符在s中出现的位置 int locs[256]; memset(locs, -1, sizeof(int) * 256); for (int i = 0; i < s.size(); i++) { // 如果s[i]在当前子串中出现过 if (locs[s[i]] > idx) { // 新子串的起始位置设为s[i]出现的位置+1 // P.S. idx是记录起始位置的前一个位置的下标 idx = locs[s[i]]; } // 如果当前子串的长度大于最大值 if (i - idx > max) { max = i - idx; } // 更新字符s[i]出现的位置 locs[s[i]] = i; } return max; } };
leetcode-----------Longest Substring Without Repeating Characters
标签:leetcode longest substring wi
原文地址:http://blog.csdn.net/chenxun_2010/article/details/43165585