Longest Substring Without Repeating Characters
题目:
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
解答:
1 public class Solution { 2 3 public static void main(String[] args) { 4 String s = "abca"; 5 System.out.println(s); 6 } 7 8 public int lengthOfLongestSubstring(String s) { 9 int[] charMap = new int[256]; 10 Arrays.fill(charMap, -1); 11 12 int i = 0; 13 int maxLen = 0; 14 for(int j = 0; j < s.length(); j++) { 15 if(charMap[s.charAt(j)] >= i) { 16 i = charMap[s.charAt(j)] + 1; 17 } 18 19 charMap[s.charAt(j)] = j; 20 maxLen = Math.max(j-i+1, maxLen); 21 } 22 23 return maxLen; 24 } 25 }
积沙成塔