问题描述:
重点:1,longest substring 2, no repeating characters
解法一:
class Solution {
public int lengthOfLongestSubstring(String s) {
Set<Character> substring=new HashSet();
int i=0,j=0,length=0,n=s.length();
while(i<n&&j<n)
{
if(!substring.contains(s.charAt(j)))
{
substring.add(s.charAt(j++));
length=Math.max(length,j-i);
}
else
{
substring.remove(s.charAt(i++));
}
}
return length;
}
}
采用滑动窗口,对于原string,用i和j来界定考察的左右边界,如果没有重复!substring.contains(),则substring.add(); 反之,如果发现有重复内容,将移动窗口向右移动一位,并且将最左侧的元素删除,i++。
采用HashSet的数据结构,关于HashSet可以参考http://www.importnew.com/6931.html
Set的集合里不允许对象有重复的值,HashSet和HashMap的区别可以参考:
解法二:使用HashMap算法
class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length(), ans = 0;
Map<Character, Integer> map = new HashMap<>(); // current index of character
// try to extend the range [i, j]
for (int j = 0, i = 0; j < n; ) {
if (map.containsKey(s.charAt(j))) {
i = Math.max(map.get(s.charAt(j))+1, i);
}
map.put(s.charAt(j), j++ );
ans = Math.max(ans, j - i );
}
return ans;
}
}
这样的算法的时间复杂度会降低,使用了HashMap的数据结构,其中的key是character类型的,value是Integer类型;之前采用的HashSet的数据结构,最坏的情况下需要O(2n),因为i和j分别访问一遍s。当下的算法只是j访问s,然后利用i在map结构中做标记,直接进行移动而不需要删除操作,将时间复杂度降到了O(n)