3. Longest Substring Without Repeating Characters

来源:互联网 发布:数据下载网站 编辑:程序博客网 时间:2024/05/29 17:44

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.


1.解题思路

package lab1;public class longestSubstring_3 {    public static void main(String[] args) {         String s = "abcabcbb";//       String s = "bbbbb";//       String s = "pwwkew";//       String s = "aa";//       String s = "sjyzaeahyh";//       String s = "uqinntq";//       String s = "abcdea";//      String s = "dvdf";        System.out.println(lengthOfLongestSubstring(s));    }    public static int lengthOfLongestSubstring(String s) {        int length = s.length();        int longest = 0;        int end = length - 1, len = length;        int last = -1;        for (int i = 0; i < length; i++) {            if (i >= end) {                if (len > longest) {                    longest = len;                }                //如果上一个串中没有重复的串,则直接i继续加一,若有重复的串则应                //该从上次最后充重复的串后面的一个字符重新开始查,这样才可以避免                //String s = "dvdf";这种情况下出错                if (last != -1) {                    i = last + 1;                    end = length - 1;                    len = length - last - 1;                    last = -1;                }            }            int index = s.indexOf(s.charAt(i), i + 1);            if (index != -1 && index <= end) {                len = len - (end - index) - 1;                end = index-1;  //应该注意对end的设置                last = i;            }        }        return longest;    }}

2.解题思路

got an interesting solution from the leetcode,as follow:

public static int lengthOfLongestSubstring(String s) {        String subString = "";        int maxLength = 0;        int index = 0;        for(int i = 0; i < s.length(); i++) {            index = subString.indexOf(s.charAt(i));            subString = subString.substring(index + 1) + s.charAt(i);            maxLength = Math.max(subString.length(), maxLength);        }        return maxLength;    }
0 0