[原题链接:] (https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/)
题目描述:
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
思路:
知道第i个位置的最长左端点left,右端点i。现在让j等于i+1这个位置,判断这个元素在不在【left~i】这个范围内,如果不在的话,继续往后移动,直到i的位置移动到长度-1;如果在的话并且在temp这个位置上,需要将left值=temp+1设置为左端点;
此程序在提交时候会出现一个小小的问题,希望网友能够解答
runtime error: index -65 out of bounds for type ‘int [27]’ (solution.cpp)
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
#define N 1000
class Solution
{
public :
int lengthOfLongestSubstring(string s)
{
int ch[27],le;
le=s.length();
for (int i = 0; i < 26; i++)
ch[i] = -1;
int index;
//cout<<le<<endl;
//cout<<s<<endl;
int lef,temp;
lef=0;
int ll=1;
for(int i=0;i<le-1;i++)//限定的是J的寻找位置,所以i<len-1,
{
//index=int(s[i]-'a');
ch[int(s[i]-'a')]=i;
int j=i+1;
temp=ch[int(s[j]-'a')];//存储的不是j位置元素的位置,因为J还没有开始,所以存储的是和j位置一样的元素,的上一个位置。。
//cout<<s[j]<<" "<<ch[int(s[j]-'a')]<<" "<<int(s[j]-'a')<<endl;
if (temp >= lef)
lef = temp+1;
//printf("%d %d\n", j, lef);
else
ll++;
}
cout<<lef<<endl;
cout<<ll<<endl;
}
};
int main()
{
Solution s;
const string str="abcabcbb";
s.lengthOfLongestSubstring(str);
}