首页 > 其他 > 详细

leetcode-----------Longest Substring Without Repeating Characters

时间:2015-01-27 09:28:01      阅读:166      评论:0      收藏:0      [点我收藏+]

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

原文:http://blog.csdn.net/chenxun_2010/article/details/43165585

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!