【LeetCode】3.Longest Substring Without Repeating Characters解题报告
tags: Two Pointers HashTable String
题目地址: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.
Solutions:
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s==null || s.length()==0){
return 0;
}
int[] hash = new int[256];
int begin=0,end=0,res=0,repeat=0;
while(end<s.length()){
if(hash[s.charAt(end++)]++>0){
repeat++;
}
while(repeat>0){
if(hash[s.charAt(begin++)]-->1){
repeat--;
}
}
res=Math.max(res,end-begin);
}
return res;
}
}
开始跟每日一题,恰好有人分享讲解视频,了解到此类String问题,有一个可用的模板。如下:
1.hashmap/hashtable
2.two pointers for size
3.condition variable
while(end<s.length()){
if(hash[end] meets req){
modify cv
}
while(cv meets condition){
places for min size of substring
if(hash[begin meets req]){
modify cv
}
places for max size of substring
}
}
Date:2017年10月14日