LeetCode第211场 两相同字符之间的最长子字符串
algorithm design
my solution
利用hash的思想,记录每个字母出现过的位置,找到并计算。
版本一:
处理哈希冲突的时候用了头插法,把新出现的元素插在头部,感觉不够高效;其实不用处理哈希冲突,这样时间每次时间复杂度可以降到O(1),空间也可以节省一个长度为300的数组。
#include <iostream>
#include <string>
#include <memory.h>
using namespace std;
class Solution {
public:
struct Node
{
int position;
int next = -1;
}strings[301];
int heads[27];
int maxLengthBetweenEqualCharacters(string s) {
int max = 0;
int has_same = 0;
memset(heads,-1,sizeof(int)*27);
for(int i = 0; i < s.length(); i++){
int tmp = s[i] - 'a';
if(heads[tmp] != -1) {
has_same = 1;
strings[i].next = heads[tmp];
int position = heads[tmp];
do{
if (max < (i-position-1))
{
max = i-position-1;
}
position = strings[position].next;
}while(position != -1);
}
heads[tmp] = i;
}
if(max == 0 && !has_same) return -1;
return max;
}
};
int main(){
char s[301];
cin>>s;
Solution sol;
cout<<sol.maxLengthBetweenEqualCharacters(s);
}
Leetcode执行结果:
版本二
只在positions中记录了26个字母第一次出现的位置。
总时间复杂度为O(n).
class Solution {
int positions[26];
public:
int maxLengthBetweenEqualCharacters(string s) {
int max = -1;
memset(positions,-1,sizeof(int)*26);
for (int i = 0; i < s.length(); i++)
{
int tmp = s[i] - 'a';
if(~positions[tmp]){
if(max < i - positions[tmp] - 1) max = i - positions[tmp] - 1;
}
else positions[tmp] = i;
}
return max;
}
};
提交结果:
referrence
直接用的遍历,遍历找出每个字母出现的头尾位置。第一个for循环O(26),第二个O(N)
错误记录
- identifier “stirng” undefined.
sol:
#include <string>
using namespace std;