1. 程式人生 > >leetcode題3 尋找字串不包含重複字元的最長子字串

leetcode題3 尋找字串不包含重複字元的最長子字串

決定每天刷一道leetcode題來維持程式設計和學習的狀態

問題表述

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.

Subscribe to see which companies asked this question

求解思路

粗看這題並不難,最開始的想法是使用分而治之策略,但是細細思考之後,這個問題分是很容易的,但是合併卻不是很容易,於是放棄了這種想法。第二種想法是動態規劃,看起來也確實是可行的,我最初也是用動態規劃來實現的,但是在測試之後卻發現有些測試用例有問題,除錯了一下才發現動態規劃的遞推關係並沒有我想象當中的簡單,典型的就是沒有想好就開始寫程式,結果做了很多無用功。最後我發現其實只要從左到右把字串掃描一遍就可以找到結果。我們維護兩個字串,一個是當前最大的字串,一個是當前的字串,最初的時候這兩個字串都為空。每掃面一個字元,如果這個字元不在字串當中,我們就把當前字串加上這個字元。如果在,當前字串就不能再往前加字元了,我們需要比較當前字串和當前最大字串。為了滿足子字串不能有重複元素的要求,我們需要把當前字串的開始地址替換掉。如此掃面一遍,就能夠得出結果。

Java程式碼

public class Solution {
    public static int lengthOfLongestSubstring(String s){
        int start = 0;
        String max = "";
        String current = "";
        int pos;
        for(int i = 0;i<s.length();i++){
            if(current.indexOf(s.charAt(i)) != -1){
                if
(current.length() >= max.length()){ max = current; } pos = current.indexOf(s.charAt(i)); current = s.substring(start + current.indexOf(s.charAt(i))+1, i+1); start = start + pos + 1; } else{ current = current + s.charAt(i); } } return max.length() > current.length()? max.length() : current.length(); } }