博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
字符串中最长不重合子串长度
阅读量:6870 次
发布时间:2019-06-26

本文共 990 字,大约阅读时间需要 3 分钟。

例子

"abmadsefadd"  最长长度为5

"avoaid"           最长长度为3

 

思路

空间换时间hashTable,起始位置设为beg。初始化全局最大值0。开辟字符数组,起初标为0。

访问数组时

  • 如果该字符在hashTable对应的哈希值为1,则计算当前位置到beg的距离,并且把beg赋值为beg+1。如果大于全局最大值,则替换全局最大值
  • 如果该字符在hashTable对应的哈希值为0,则置1

参考代码

 

#include 
using namespace std;int getMaxLen(const string &s){ int beg = 0; int span = 0; int maxspan = 0; int hashTable[128]; for (int i = 0; i < 128; ++i) hashTable[i] = 0; int lens = s.size(); for(int i = 0; i < lens; ++i) { int index = s[i]; if (hashTable[index] == 1) { span = i - beg; if (span > maxspan) maxspan = span; beg++; } else { hashTable[s[i]] = 1; } } return maxspan;}int main(){ const string a = "abmadsefadd"; const string a1 = "avoaid"; cout << getMaxLen(a) << endl; cout << getMaxLen(a1) << endl;}

 

结果

1
2
7
3

 

本文转自jihite博客园博客,原文链接:http://www.cnblogs.com/kaituorensheng/p/3822923.html,如需转载请自行联系原作者

你可能感兴趣的文章
[动态库]深入分析Windows和Linux动态库应用异同
查看>>
Linux下查看CPU信息、机器型号等硬件信息命令
查看>>
Lync Server 2013 部署 _ 部署简介及系统要求
查看>>
前端小随笔
查看>>
view属性大全
查看>>
Java文件编码示例
查看>>
CactiFans V1.0中文版发布
查看>>
HTML如何显示小于号“<”等特殊符号?
查看>>
别伤了虚拟桌面管理员的"心"
查看>>
Windows系统使用IntelliJ IDEA 搭建Hadoop的开发调试环境(一)
查看>>
yum安装lamp
查看>>
Web.Config文件中数据库连接配置
查看>>
[Unity 3D] Unity 3D 性能优化 (一)
查看>>
spring Quartz定时任务调度 时间设置
查看>>
SymmetricDS: 数据库数据同步Database synchronization
查看>>
Disabling OOM killer on Ubuntu 14.04
查看>>
VBS备份脚本
查看>>
CentOS 6.5 自动安装镜像
查看>>
Storm与Spark Streaming比较
查看>>
我的友情链接
查看>>