首页 > 代码库 > 3. Longest Substring Without Repeating Characters
3. Longest Substring Without Repeating Characters
3. Longest Substring Without Repeating Characters
DescriptionHintsSubmissionsDiscussSolution
DiscussPick One
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.
首先看到这个题就要想到怎么来处理。
O(N^2)做法
以第一层for循环的i为子串的结尾遍历一遍母串
然后pos为每一个串的开头,只要有相同的那么下一个串,结尾是i+1,已经包括了i,i跟前面的有冲突,记录为j,所以pos记录为j+1,从没冲突的开始即可。
用Max记录每一个串的最大长度:
public class Solution { public int lengthOfLongestSubstring(String s) { if(s.length()==0) return 0; int pos = 0; int Max = 1; int flag = 0; int cnt = 1; String ans = ""; for(int i = 1; i < s.length(); i++) { flag = 0; for(int j = pos; j < i; j++) { if(s.charAt(i) == s.charAt(j)) { flag = 1; pos = j+1;//如果有相同的,那么下一个遍历的点就要跳过这个,集合不能包括这个 break; } cnt++; } Max = Max>cnt?Max:cnt; cnt = 1; } return Max; }}
3. Longest Substring Without Repeating Characters
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。