Longest Substring Without Repeating Characters (FROM LeetCode)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Xminyang/article/details/80339481

Longest Substring Without Repeating Characters

描述:

Given a string, find the length of the longest substring without repeating characters.

样例:

Given “abcabcbb”, the answer is “abc”, which the length is 3.
Given “bbbbb”, the answer is “b”, with the length of 1.
Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.


解体思路:

假设输入为string s。新加变量res[],大小为s.length(),其中res[i]用以记录s的前i个元素中最大的不重复子串的长度;最后,再确定res[]的最大值即可。

VS源码:

#include <string>
#include <iostream>
using namespace std;

class Solution {
public:
    int LengthOfLongestSubstring(string s) {
        int n = s.length();
        if (n == 0)//s为null
            return 0;
        int *res;
        res = (int*)malloc(n * sizeof(int));//分配空间
        int i, max=1,j;
        for (i = 1;i < n;++i)//初始化res
            res[i] = 0;
        res[0] = 1;
        for (i = 1;i < n;++i) {         
            if (s[i] != s[i - 1]) {//当前字符与上一个字符不等
                res[i] = 1;
                for (j = i - 1;j >= i - res[i - 1];--j) {
                    if (s[i] != s[j])
                        ++res[i];
                    else
                        break;
                }       
            }
            else//当前字符与上一个字符相等,则从1开始计数
                res[i] = 1;
        }
        for (i = 0;i < n;++i)//查询最大值值
            if (res[i] > max)
                max = res[i];
        free(res);//释放空间,以防内存泄漏
        res = NULL;//防止“野指针”
        return max;
    }

};

int main()
{
    Solution *s = new Solution();
    int max = 0;
    max = s->LengthOfLongestSubstring(string("dvdf"));
    cout << "max=" << max << endl;
    return 0;
}


特殊输入测试用例:
输入:“” ; 输出:0
输入:“dvdf” ; 输出:3

阅读更多

没有更多推荐了,返回首页