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.
解题思路:
首先定义两个整形变量p,q用来保存子串的下标,p表示子串的首字母下标,q表示子串的尾字母下标。子串A(p,q)需要满足性质:不含有重复的字母。
每经过一次循环,q往后移动一位即q+1;p的值是否变化取决于下标q所指向的那个元素是否和子串的元素重复,如果不重复,那么p值不变;如果有重复,比如子串中有下标为k的元素与之重复,那么为了维护子串的性质,需要将p值修改为k+1,使得子串A(p,q)维护的元素不重复的性质。变量max表示循环后的最大子串长度。算法的时间代价:O(n)
相关代码如下:
public class Solution { public int lengthOfLongestSubstring(String s) { if(s==null || s.equals("")){ return 0; } int p=0,q=0; //p,q用于保存子串的下标 int max = 1; //max用于保存子串的最大长度 for(int i=1;i<s.length();i++){ char ch = s.charAt(i); q = q+1; for(int j=p;j<i;j++){ if(ch == s.charAt(j)){ p = j+1; break; } } max = (q-p+1)>max?(q-p+1):max; } return max; } }