3. Longest Substring Without Repeating Characters
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3. Longest Substring Without Repeating Characters相关的知识,希望对你有一定的参考价值。
3. Longest Substring Without Repeating Characters
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的主要内容,如果未能解决你的问题,请参考以下文章
longest-substring-with-at-least-k-repeating-characters
LeetCode 395. Longest Substring with At Least K Repeating Characters
395. Longest Substring with At Least K Repeating Characters
3. Longest Substring Without Repeating Characters
Leetcode: Longest Substring with At Least K Repeating Characters