Leetcode longest-substring-without-repeating-characters(java实现)

题目描述

第一种解题方法

题目是求最长无重复子字符串
1.采用定义一个256位大小的整型数组来代替HashMap,保证了无重复性,256位长度是因ASCII表共能表示256个字符来记录所有字符。
2.定义标记无重字符串最左边的位置和最终结果长度的int整型变量,left和res,遍历整个字符串:
第一种情况:一直遍历没有遇到无重子串,则返回结果等于i - left +1,i为无重子串最右边的位置;
第二种情况:在遍历过程中,出现了遇见重复字符的情况,此时返回重复字符第一次定义的位置,也就是此时哈希表里该字符的对应值小于left,此时res返回max(res,i-left)的结果时。返回的仍是上次遍历得到的res值,因为此时i-left<res;

public int longest_substr(String s){
		int [] m = new int [256];
		Arrays.fill(m, -1);
		int res = 0;
		int left =-1;
		for (int i = 0;i<s.length();i++){
			left = Math.max(left, m[s.charAt(i)]);
			m[s.charAt(i)] = i;
			res = Math.max(res, i-left);
		}
		return res;
		

第二种方法

采用hashset,与第一种类似,相比第一种方法,它是遍历到到重复字符就将第一次遇到的该字符从hashset中移除。

public int lengthOfLongestSubstring(String s) {
       int n = s.length(),left = 0,right = 0,res = 0;
	   HashSet<Character> h = new HashSet<Character>();
		while(right < n){
			if (!h.contains(s.charAt(right))){
				h.add(s.charAt(right));
				right++;
				res = Math.max(res, h.size());
				
			}else{
				h.remove(s.charAt(left));
				left++;
			}
		}
		return res;
    }

猜你喜欢

转载自blog.csdn.net/qq_35135923/article/details/84893640