3. Longest Substring Without Repeating Characters
来源:互联网 发布:bi开源框架 php 编辑:程序博客网 时间:2024/06/05 22:55
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, 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.
package November;public class LongestSubstringWithoutRepeatingCharacters {public static int lengthOfLongestSubstring(String s) {if(s==null||s.isEmpty())return 0;int max = 1;int index = 1;int sum = 1;while (index < s.length()) {int pos=existInSubstring(s,index-sum,index-1,s.charAt(index));if (pos==-1) {sum++;if(sum>max){//这里需要注意,及时更新max值max=sum;}index++;} else {if (sum > max) {max = sum;}sum = 1;index=pos+2;//这里需要注意,回退点不是index+1,而是上一个重复的地方,例如dvdf,应该是3,而不是2}}return max;}public static int existInSubstring(String s, int start, int end,char c) {for (int index = start; index <= end; index++) {if (s.charAt(index) == c)return index;}return -1;}public static void main(String[] args) {//String s1 = "abcabcbb";//String s2 = "bbbbb";//String s3 = "pwwkew";String s4="au";String s5="dvdf";//System.out.println(lengthOfLongestSubstring(s1));//System.out.println(lengthOfLongestSubstring(s2));//System.out.println(lengthOfLongestSubstring(s3));System.out.println(lengthOfLongestSubstring(s4));System.out.println(lengthOfLongestSubstring(s5));}}
阅读全文
0 0
- [LeetCode]3.Longest Substring Without Repeating Characters
- LeetCode 3.Longest Substring Without Repeating Characters
- LeetCode --- 3. Longest Substring Without Repeating Characters
- 3.Longest Substring Without Repeating Characters
- [Leetcode] 3. Longest Substring Without Repeating Characters
- 3.Longest Substring Without Repeating Characters
- 3. Longest Substring Without Repeating Characters
- 3.Longest Substring Without Repeating Characters
- 3.Longest Substring Without Repeating Characters
- 3.Longest Substring Without Repeating Characters
- 3. Longest Substring Without Repeating Characters
- [leetcode] 3.Longest Substring Without Repeating Characters
- 3.Longest Substring Without Repeating Characters
- [leetcode] 3. Longest Substring Without Repeating Characters
- 3. Longest Substring Without Repeating Characters
- [Leetcode]3. Longest Substring Without Repeating Characters
- leetcode 3. Longest Substring Without Repeating Characters
- 【Leetcode】3. Longest Substring Without Repeating Characters
- Mongodb
- ZOJ 3983 Crusaders Quest
- AndroidStudio项目打包成jar
- spring boot框架学习9-spring boot的web开发(5)-错误解决及跳转页面
- IDEA配置已部署项目DEBUG
- 3. Longest Substring Without Repeating Characters
- Tomcat 基础配置及原理 (一)
- 斯坦福大学机器学习笔记——逻辑回归、高级优化以及多分类问题
- 动态的把数据显示在table中,点击某一行的删除按钮实现该行的删除(通过ajax实现页面的无刷新加载)
- (含例子)Math.random()随机数的使用
- java基础6:io流对象之字符输入输出流
- Android 用adb 打印linux内核调试信息dmesg和kmsg命令
- 用两个栈实现队列
- MarkDown编辑器常用语法