标签:
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.
解题思路 :利用hashmap, 记录字符是否出现过,如果出现过将子序列的起始位置移动到已经存在的字符的后一个位置。
1 public class Solution { 2 public int lengthOfLongestSubstring(String s) { 3 if (s == null || s.length() == 0) { 4 return 0; 5 } 6 int[] map = new int[256]; 7 Arrays.fill(map, -1); 8 int left = 0, right = 0; 9 int result = 0; 10 for (right = 0; right < s.length(); right++) { 11 int ch = s.charAt(right); 12 while (map[ch] != -1 && left < right) { 13 int temp = s.charAt(left); 14 ++left; 15 map[temp] = -1; 16 } 17 map[ch] = 1; 18 result = Math.max(result, right - left + 1); 19 } 20 return result; 21 } 22 }
Longest Substring Without Repeating Characters
标签:
原文地址:http://www.cnblogs.com/FLAGyuri/p/5797146.html