Longest Substring Without Repeating Characters
题目地址:
https://leetcode.com/problems/longest-substring-without-repeating-characters/#/description
题目:
解题思路:
这道题用一个map来存char和之前出现过的index。
代码:
https://leetcode.com/problems/longest-substring-without-repeating-characters/#/description
题目:
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.解题思路:
这道题用一个map来存char和之前出现过的index。
代码:
public class LongestSubstringWithoutRepeatingCharacters { public static void main(String[] args){ LongestSubstringWithoutRepeatingCharacters longestSubstringWithoutRepeatingCharacters = new LongestSubstringWithoutRepeatingCharacters(); String s = "ggububgvfk"; int rst = longestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring(s); System.out.println(rst); } public int lengthOfLongestSubstring(String s) { if(s == null || s.length() == 0){ return 0; } String rst = ""; Map<Character, Integer> map = new HashMap<>(); int left = 0; for(int i = 0; i <= s.length() - 1; i++){ char c = s.charAt(i); if(!map.containsKey(c)){ map.put(c, i); String temp = s.substring(left, i + 1); rst = temp.length() > rst.length() ? temp : rst; } else{ left = Math.max(left, map.get(c) + 1); String temp = s.substring(left, i + 1); rst = temp.length() > rst.length() ? temp : rst; map.put(c, i); } } return rst.length(); } }

Comments
Post a Comment