
leetcode练习3(查找特定字符串)
发布日期:2021-05-06 14:09:42
浏览次数:16
分类:精选文章
本文共 1758 字,大约阅读时间需要 5 分钟。
题目:给定一个字符串,找出不含有重复字符的最长子串的长度。
题解(1):写一个判断字符串是否有相同字符的函数,再写一个函数能够将字符串拆分成所有可能的子字符串并进行相同字符存在性判断,比较所有无相同字符串的字符串长度,返回最大字符串长度。
#include "iostream"using namespace std;#include"unordered_map"class solution{ public: string str; solution(string strs) { str = strs; } int res = 0; int j=0; bool judge(string str) //用于判断该字符串是否含有相同字符 { for (int i = 0;i < str.length();i++) { for (int j = 0;j < i;j++) { if (str[j] == str[i])return false; } } return true; } int count() //将字符串分成子字符串,进行判断,返回结果 { int res = 0; string re=""; string substr; for (int i = 0;i < str.length();i++) { for (int j = 0;j < i;j++) { substr = str.substr(j, i); if (judge(substr) == true && res < substr.length()) { res = substr.length(); re = substr; } } } cout << res << endl << re << endl; return res; }};int main(){ solution solu("adkjfabcdefa"); solu.count();}
题解(2)滑动窗口法,利用哈希集合
#include "iostream"using namespace std;#include"unordered_map"#include"unordered_set"class solution{ public: string str; solution(string strs) { str = strs; } int count() { string result; unordered_mapm; int start = 0; int end = 0; int res = 0; while (end < str.length()) { if (m.find(str[end]) != m.end() && m[str[end]] >= start) { if (res < end - start) { res = end - start; cout << start << endl << end << endl; result = str.substr(start, end-2); //第一个参数是起始位置,第二个参数是长度 } start++; } m[str[end]] = end; end++; } cout << result; return res; }};int main(){ solution solu("adkjfabcdefa"); cout << solu.count();}
发表评论
最新留言
感谢大佬
[***.8.128.20]2025年03月17日 02时59分58秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
团体程序设计天梯赛-练习集 L1-006 连续因子 (20分)
2019-03-04
编程技巧妙用
2019-03-04
团体程序设计天梯赛-练习集 L1-023 输出GPLT (20分)
2019-03-04
团体程序设计天梯赛-练习集 L2-007 家庭房产 (25分) 并查集思想+坑点分析
2019-03-04
暴打算法:王者级数据结构与LeetCode笔记,一路绿灯杀进字节Java岗
2019-03-04
团体程序设计天梯赛-练习集 L2-020 功夫传人 (25分) dfs深搜
2019-03-04
不愧是Alibaba技术官,随便甩出本kafka限量笔记,都火遍全网
2019-03-04
爱了!腾讯技术官手写SpringCloud笔记,GitHub已标星81.6k
2019-03-04
惊喜万分!全靠这份999页Java面试宝典,我刚拿到美团offer
2019-03-04
三个步骤,一天就搞定了MySQL,顺利入职京东天猫
2019-03-04
蘑菇街被裁,奋战7个月拿下字节跳动offer
2019-03-04
三面阿里Java岗被挂,竟获内推名额,历经5面拿下口碑offer
2019-03-04
整合:2021年已收录GitHub的最新、最全、最实用的Java岗面试真题
2019-03-04
限时开源!公布半小时下载量达10W:阿里大牛出品「MyCat笔记」
2019-03-04
阿里Java全线成长宝典,从P5到P8一应俱全
2019-03-04
Java程序员面试涨薪手册,字节21火山版强势来袭
2019-03-04
世界级安全专家整理出的Linux高级笔记,限时开源
2019-03-04
GitHub访问破百万,阿里神作:并发实现原理JDK源码笔记
2019-03-04
阿里SpringBoot全栈小册!Github标星百万,限时开源
2019-03-04
程序员职场经验
2019-03-04