您當前的位置:首頁 > 寵物

無重複字元的最長子串(滑動視窗)

作者:由 工藤新木 發表于 寵物時間:2020-04-24

題目描述:

LeetCode_3:無重複字元的最長子串

給定一個字串,請你找出其中不含有重複字元的 最長子串 的長度。

示例 1:

輸入: “abcabcbb”

輸出: 3

解釋: 因為無重複字元的最長子串是 “abc”,所以其長度為 3。

示例 2:

輸入: “bbbbb”

輸出: 1

解釋: 因為無重複字元的最長子串是 “b”,所以其長度為 1。

示例 3:

輸入: “pwwkew”

輸出: 3

解釋: 因為無重複字元的最長子串是 “wke”,所以其長度為 3。

請注意,你的答案必須是 子串 的長度,“pwke” 是一個子序列,不是子串。

主要思路:

就按照滑動視窗的思路來做即可,其實也就是雙指標法,題目不算難,但做完用了半小時。

這道題目犯錯了的有兩個注意點:

對於長度為0的校驗;

set裡放的是String型別,刪的時候也必須是String型別,用char是刪不掉的,不會自動幫你轉換為String!

解題如下:

class

Solution

{

public

int

lengthOfLongestSubstring

String

s

{

// 一些基本校驗

if

s

length

()

==

0

{

return

0

}

int

start

=

0

int

end

=

0

Set

<

String

>

set

=

new

HashSet

<>();

set

add

String

valueOf

s

charAt

0

)));

int

max

=

1

while

end

+

1

<

s

length

())

{

// 不重複則加入set

if

(!

set

contains

String

valueOf

s

charAt

end

+

1

))))

{

set

add

String

valueOf

s

charAt

end

+

1

)));

end

++;

max

=

end

-

start

+

1

>

max

end

-

start

+

1

max

}

else

{

// 找到重複字元及前的全部刪除

while

s

charAt

start

!=

s

charAt

end

+

1

))

{

set

remove

String

valueOf

s

charAt

start

)));

start

++;

}

set

remove

String

valueOf

s

charAt

start

)));

start

++;

set

add

String

valueOf

s

charAt

end

+

1

)));

end

++;

max

=

end

-

start

+

1

>

max

end

-

start

+

1

max

}

}

return

max

}

}

父貼子:工藤新木:滑動視窗演算法

如有錯誤,請更正指出,謝謝!

標簽: end  String  start  set  charAt