LeetCode Longest Substring Without Repeating Characters

来源:互联网 发布:pages有windows版吗 编辑:程序博客网 时间:2024/06/06 03:27

鄙人 刘天昊 csdn新用户 用博客来记录自己的学习过程也希望和网络上志同道合的朋友做一些交流


leetcode篇因为研究生本科都不是cs出生,所以自学数据结构,所有的leetcode都是C语言实现


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

Examples:

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.

在一个字符串中找出最长不重复子字符串的长度(最长,子字符串,不重复,长度)

把握关键字(子字符串不是子序列)


//重新解释一下这题并且po上自己的代码

说下自己的思路

首先我们用个数组hash【128】来记录字符出现的位置,这种哈希的思想需要掌握(不会面壁)

然后我们定义两个位置(类似指针的思想指向字符串的位置)end,start

接着定义答案因为要求是最大

我们开始遍历字符串每次都更新当前字符的位置,如果遇到不为空的字符会与已经存在hash里的pos冲突

因为冲突所以一定有了重复的元素

我们为了确保start必须向前移动用了这句

 start = max( start , hash[ s[ i ] ] + 1 );

class Solution {public:    int lengthOfLongestSubstring(string s) {        vector<int>hash(128,-1);        int start=0;        int end=0;        int ans=0;        for(int i=0;i<s.size();i++)        {            if( hash[ s[ i ] ] != -1 )            {                start = max( start , hash[ s[ i ] ] + 1 );            }            hash[ s[ i ] ] = i;            end = i;            ans = max ( ans , end - start + 1 );        }        return ans;    }};



这道题我是看了题目后面提示的。。。也就是维护窗口大小,这个就简单注释下代码好了-。-

#define Max(a,b) a>b?a:b//方便int lengthOfLongestSubstring(char* s) {    int Index[256];//这里经常字符串经常使用的方法因为char型是0-255所以可以定义整形数组来记录     memset(Index,-1,sizeof(Index));//全部赋值-1;    int start=0;//定义窗口的起始位置    int longest=0;//定义用来记录长度    for(int end=0;*(s+end)!='\0';end++)    {        start=Max(Index[s[end]]+1,start);//更改起始点,举个例子abcabc当第二个a出现时因为Index[a]=0(因为第一个a的索引被记录在Index中所以start更新到1——-start到end变为bca没有重复的字符(不知道这样说能不能理解)        Index[s[end]]=end;//记录字符的索引        longest=Max(longest,end-start+1);//求最大长度    }    return longest;}

这题就没有考虑暴力AC了因为复杂度可能到O(n3)所以没有考虑暴力AC

那么还是欢迎讨论交流指正

1 0
原创粉丝点击