【LeetCode3】Longest Substring Without Repeating Characters★★

题目描述:

【LeetCode3】Longest Substring Without Repeating Characters★★

解题思路:

  借用网上大神的思想:the basic idea is, keep a hashmap which stores the characters in string as keys and their positions as values, and keep two pointers which define the max substring. move the right pointer to scan through the string , and meanwhile update the hashmap. If the character is already in the hashmap, then move the left pointer to the right of the same character last found. Note that the two pointers can only move forward.

  大意:基本思想是,用一个hashmap存储字符串,把字符串的每一个字符当作key,字符所在的位置作为value,并维护两个指针,两个指针之间就是不存在重复字符的字串,而此题求的是满足这样要求的最大字串。然后,移动右指针遍历字符串,同时更新hashmap。如果遍历到的字符已存在于hashmap,就移动左指针到最后一次出现该字符的右边一个位置。注意,两个指针都只能向右移动,不能回退。

  以字符串abbc为例:

【LeetCode3】Longest Substring Without Repeating Characters★★

Java代码:

 import java.util.HashMap;
import java.util.Map; public class LeetCode371 {
public static void main(String[] args) {
String s="abba";
System.out.println(s+"最长不存在重复字符的字串长度是:"+new Solution().lengthOfLongestSubstring(s));
}
}
class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character,Integer> map=new HashMap<Character,Integer>();
int max=0;
for(int left=0,right=0;right<s.length();right++){
if(map.containsKey(s.charAt(right)))
left=Math.max(left,map.get(s.charAt(right))+1);
map.put(s.charAt(right), right);
max=(right-left+1)>=max?(right-left+1):max;
}
return max;
}
}

程序结果:

【LeetCode3】Longest Substring Without Repeating Characters★★

上一篇:learning docker steps(3) ----- docker services 初次体验


下一篇:【转】TCP三次握手过程