1. 程式人生 > >【LeetCode】Longest Substring Without Repeating Characters

【LeetCode】Longest Substring Without Repeating Characters

order rip rep pri addclass ring 存在 i+1 math

問題描寫敘述

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.

Input:abcabcbb
Output:3

意:查找給定字符串中最長的無反復字符的子串

算法思想

對於字符串S<a1,a2,a3,a4,a3>,假設我們從左向右掃描字符串,那麽當遇到第二個a3時,對於a4及其之前的全部子串的長度一定小於等於a4

所以不必要每次從頭查找子串。
假設沒有反復字符。那麽i=0。j=n, 長度為j-i+1
假設存在反復字符,那麽長度為j-i(不包括反復字符本身),然後我們將i更新為反復字符中的第一個,上例中當遇到第二個a3時,i=2。


假設我們使用hashmap推斷反復字符的出現,須要推斷反復字符是否出如今i與j之間。

算法實現

import java.util.HashMap;
public
class Solution { public static int lengthOfLongestSubstring(String s) { int i = 0; int j = 0; int loc = 0; int nowCount = 0, tmpCount = 0; HashMap<Character, Integer> holder = new HashMap<Character, Integer>(); int n = s.length(); while
(j < n) { Character c = s.charAt(j); if (!holder.containsKey(c) || (loc = holder.get(c)) < i) { tmpCount = j - i + 1; } else { tmpCount = j - i; i = loc + 1; } nowCount = tmpCount > nowCount ?

tmpCount : nowCount; holder.put(c, j); j++; } return nowCount; } public static void main(String[] args) { String s = "abcabc"; System.out.println(lengthOfLongestSubstring(s)); } }

算法時間

T(n) = O(n);//忽略hash查找的時間

演示結果

3

【LeetCode】Longest Substring Without Repeating Characters