LeetCode算法问题7 —— Longest Substring Without Repeating Characters
来源:互联网 发布:携程php招聘 编辑:程序博客网 时间:2024/06/06 08:41
问题描述
简单来说,就是找一个字符串中最长的不存在重复字母的子串长度
自然遍历字符串一遍是不可避免的,自然,我的想法就是建立一个临时字符串变量temp存储当前遍历到的无重复字母的字符串,在对给定字符串进行遍历的时候,可能会出现几种情况:
- 不是重复字母,则temp将其加上
- 是重复字母,则:
a. 首先比较当前temp长度和目前所遇到的最长长度哪个大,若是temp较长则替换
b. 如果重复字母出现在temp的中间,则中间及以前的字符串都必须剔除,新的temp是重复字母之后的子串与重复字母的合
c. 如果重复字母出现在末位,则temp元素全部替换
下面是源代码:
int lengthOfLongestSubstring(string s) { string temp; int biggestLength = 0; size_t pos; for (int i = 0; i < s.size(); i++) { pos = temp.find(s[i]); if (pos != string::npos) { if (temp.size() > biggestLength) biggestLength = temp.size(); /* The repeating character isn't in the end of the string "answer" */ if (pos != temp.size() - 1) { temp = temp.substr(pos + 1) + s[i]; } else { temp = s[i]; } } else { temp += s[i]; } } if (temp.size() > biggestLength) biggestLength = temp.size(); return biggestLength; }
时间复杂度是O(n),暂且没有找到更好的办法,希望能获取大家的建议
阅读全文
0 0
- LeetCode算法问题7 —— Longest Substring Without Repeating Characters
- LeetCode算法题——Longest Substring Without Repeating Characters
- 数据结构与算法[LeetCode]—Longest Substring Without Repeating Characters
- LeetCode —— Longest Substring Without Repeating Characters
- LeetCode——Longest Substring Without Repeating Characters
- LeetCode——Longest Substring Without Repeating Characters
- [LeetCode]——Longest Substring Without Repeating Characters
- leetcode 003 —— Longest Substring Without Repeating Characters
- LeetCode——Longest Substring Without Repeating Characters
- LeetCode题解——3Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters —— Leetcode
- LeetCode——Longest Substring Without Repeating Characters
- #3 LeetCode——Longest Substring Without Repeating Characters
- [leetcode Q3] —— Longest Substring Without Repeating Characters
- leetcode——Longest Substring Without Repeating Characters
- leetcode——Longest Substring Without Repeating Characters
- leetcode——3 Longest Substring Without Repeating Characters
- LeetCode——3. Longest Substring Without Repeating Characters
- python set
- service的基本运用
- PL/SQL
- linux 鸟哥私房菜笔记篇
- Rxjava2-小白快速入门
- LeetCode算法问题7 —— Longest Substring Without Repeating Characters
- Struts2简介
- C++ MFC / VS2013 之十四 (对话框:消息对话框)
- Normalization(标准化)的原理和实现详解
- 常用词汇收集
- 文字反转 字体变颜色
- 前端工具
- Win10 Edge浏览器假死解决方案
- js 存贮-storage