leetcode-3 最长无重复字串
2024-09-03 05:03:09
3. Longest Substring Without Repeating Characters
题面
Given a string, find the length of the longest substring without repeating characters.
给定字符串,找到最长无重复字串的长度
样例
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is"abc"
, with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is"b"
, with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is"wke"
, with the length of 3.
Note that the answer must be a substring,"pwke"
is a subsequence and not a substring.
思路
开始的思路是,蠢笨的滑动窗口
1.遍历字符串
2.以每个字符串为基准,向后搜索,暂存不重复的字符,遇到重复字符,结束内循环,统计不重复字符个数,更新结果。
时间复杂度:O(n3)
空间复杂度:> O(n)
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int res = ;
int len = s.length();
if(len <= )
return len;
for(int i=; i<len; i++)
{
string tmpStr = "";
int k = i;
while(!find(tmpStr, s[k]) && k < len)
{
tmpStr += s[k];
k++;
}
if(tmpStr.length() > res)
res = tmpStr.length();
}
return res;
}
//搜索元素是否存在(已经记录过)
bool find(string str, char c)
{
for(int j=; j<str.length(); j++)
if(str[j] == c)
return true;
return false;
}
};
优化?改进搜索复杂度
使用string find(char c)函数来替换我自己实现的find()函数,果然快了好多。
时间复杂度:大于O(n2) 小于 O(n3)
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int res = ;
int len = s.length();
if(len <= )
return len;
for(int i=; i<len; i++)
{
string tmpStr = "";
int k = i;
//使用string find函数替换我的find函数
while(tmpStr.find(s[k]) == tmpStr.npos && k < len)
{
tmpStr += s[k];
k++;
}
if(tmpStr.length() > res)
res = tmpStr.length();
}
return res;
}
};
当我使用unordered_map<char, char>来存储元素后,发现用时和空间没有继续减小,反而增大了许多,几乎与最开始采用的方法一致了。比较奇怪!
那么有没有办法消除一层循环呢?
待续......
最新文章
- WinformWPF 多线程访问控件【转】
- ACM: FZU 2112 Tickets - 欧拉回路 - 并查集
- 关于string,我今天科普的
- 【Selenium】2.安装Selenium IDE和 FireBug
- SQL 递归 可以用于权限查找。迭代自身没有用递归函数。
- 在http编程的门口----飞牛网自动下单,查单
- JavaScript运行原理解析
- wpf软件某些分辨率下文字模糊解决方法
- Python开发工具PyCharm个性化设置
- sqlserver配置允许快照隔离
- internal table operation
- EntityFramework安装和EF升级方法
- win7+php5.3.10下安装memcache (转)
- 洛谷P1038神经网络
- poj-2253-poj-1797_最短路练习
- switch case :在JDK 7中,又加入了对String类型的支持,从此不用再写If-Else来判断字符串了
- CentOS7.2编译配置LNMP环境(MySQL5.7.20,PHP7.0.24)
- 【洛谷】P1541 乌龟棋(四维背包dp)
- python-网易云简单爬虫
- AOJ.综合训练.2016-12-1