当前位置:网站首页>leetcode精选TOP面试题_字符串
leetcode精选TOP面试题_字符串
2022-07-19 10:41:00 【身影王座】
3. 无重复字符的最长子串
什么是滑动窗口?
其实就是一个队列,比如例题中的 abcabcbb,进入这个队列(窗口)为 abc 满足题目要求,当再进入 a,队列变成了 abca,这时候不满足要求。所以,我们要移动这个队列!
如何移动?
我们只要把队列的左边的元素移出就行了,直到满足题目要求!一直维持这样的队列,找出队列出现最长的长度时候,求出解!
时间复杂度:O(n)。
Java解决方法
需要一种数据结构来判断是否有重复字符:HashSet。
class Solution {
public int lengthOfLongestSubstring(String s) {
Set<Character> ss = new HashSet<Character>();
int slen = s.length();
int length = 0;
int maxLength = 0;
for(int i = 0; i < slen; i++)
{
//退出队列中的一个元素
if(i != 0)
{
ss.remove(s.charAt(i - 1));
}
//向队列中加入元素,加入时HashSet会自动判断有无重复
while(length < slen && ss.add(s.charAt(length)))
{
length++;
}
if(maxLength < length - i)
{
maxLength = length - i;
}
}
return maxLength;
}
}
C语言解决方法
bool haveSame(char *ss, int start, int end, char c)
{
int i = start;
if(end == 0)
{
return true;
}
while(i < end && ss[i] != c)
{
i++;
}
if(i >= end)
{
return true;
}
else
{
return false;
}
}
int lengthOfLongestSubstring(char * s){
char *ss = NULL;
int len;
len = strlen(s);
ss = (char *)malloc(len * sizeof(char));
int length = 0;
int maxLength = 0;
for(int i = 0; i < len; i++)
{
//向队列中加入元素,加入时HashSet会自动判断有无重复
while(length < len && haveSame(ss, i, length, s[length]))
{
ss[length] = s[length];
length++;
}
if(maxLength < length - i)
{
maxLength = length - i;
}
}
return maxLength;
}
边栏推荐
- 为中小企业ERP夯实基础,华为创新解决方案有何特别之处?
- 面对复杂问题时,系统思考助你理解问题本质
- onnx 模型导出为 trt 模型
- 北森控股IPO:三年合计亏损41.15亿,此前9轮融资合计28.4亿元
- Reading notes - shopping mall
- 30 times performance improvement -- implementation of MyTT index library based on dolphin DB
- 如何用PHP解决高并发与大流量问题
- I used Kaitian platform to make a string check API [Kaitian apaas battle]
- User authentication of NGFW
- Automatic metallic surface defect detection and recognition with revolutionary neuralnetworks
猜你喜欢
随机推荐
华为占据折叠手机市场半数份额,证明它在高端市场的地位无可替代
记录一下把域名从阿里云服务商转入到华为云
侧边栏布局
MongoDB 安全认证
RK3399平台开发系列讲解(中断篇)13.17、中断处理方式的汇总
DashboardClient
一文让你学会使用flowable工作流
ModelBox端云协同AI开发套件(RK3568)试用记录(一)
Upgrading thinking from engineer to technical leader
Write a JS tool library and publish it to NPM, and add detailed tutorials and solutions for eslint and jest unit testing
熔断、降级 Sentinel
View files in different branches without switching branches
聚焦数据|海泰方圆直击证券行业数据安全治理建设思路
【ManageEngine】SIEM为企业带来的价值
网关Gateway的介绍(下)
HCIP之OSPF
Magic curve of product development that PM must master
0055 PHP language introduction and HelloWorld
Dynamic memory management
Fully Convolutional Networks for Surface Defect Inspection in IndustrialEnvironment-论文阅读笔记