leetcode003:Longest Substring Without Repeating Characters

来源:互联网 发布:什么值得买app源码 编辑:程序博客网 时间:2024/06/15 09:35

问题描述

Longest Substring Without Repeating Characters
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.

思路描述

寻找字符串中最长的非重复字符的子串。思路:abcdefc,出现重复字符则截断从重复字符后一个字符开始的子串“defc”继续统计非重复字符子串,最终达到最长非重复字符子串!

代码

class Solution {public:    int lengthOfLongestSubstring(string s) {        string s1 ;        int ans=0;        int count=0;        int idx;        for (int i = 0; i < s.length(); i++)        {            if ((idx = s1.find(s[i], 0)) == string::npos)            {                s1 += s[i];                count++;            }            else            {                if (count>ans) ans = count;                s1 = s1.substr(idx + 1) + s[i];                count = s1.length();            }        }        return count > ans ? count : ans;    }};
0 0
原创粉丝点击