forked from IDeserve/learn
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestSubstringWithMUniqueCharacters.java
More file actions
90 lines (72 loc) · 1.81 KB
/
LongestSubstringWithMUniqueCharacters.java
File metadata and controls
90 lines (72 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package questions.virendra;
import java.util.HashMap;
import java.util.HashSet;
public class LongestSubstringWithMUniqueCharacters {
public static String solution(String s, Integer m) throws Exception
{
/* HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
int uniqChars = 0;
int size = s.length();
for(int i=0; i<size;i++)
{
int ch = (int)s.charAt(i);
if(!hash.containsKey(ch))
{
uniqChars++;
hash.put(ch, 1);
}
else
{
int temp = hash.get(ch);
hash.put(ch,++temp);
}
}
if(uniqChars < m)
{
throw new Exception("only " + uniqChars + " unique characters are found");
}*/
int start =0, end=0, windowSize =1, windowStart = 0;
int size = s.length();
HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
int ch = (int)s.charAt(0);
hash.put(ch, 1);
for(int i=1; i<size;i++)
{
ch = (int)s.charAt(i);
if(!hash.containsKey(ch))
{
hash.put(ch, 1);
}
else
{
int temp = hash.get(ch);
hash.put(ch,++temp);
}
end++;
//move start forward if number of unique characters is greater than m
while(!isLessThanM(hash,m))
{
int temp = hash.get((int)s.charAt(start));
hash.put((int)s.charAt(start),--temp);
start++;
}
if(end-start+1 >windowSize)
{
windowSize = end-start + 1;
windowStart = start;
}
}
return s.substring(windowStart, windowStart+windowSize);
}
public static boolean isLessThanM(HashMap<Integer,Integer> hash, Integer m)
{
int count =0;
for(Integer key:hash.keySet())
if(hash.get(key) > 0) count++;
return (count <= m);
}
public static void main(String args[]) throws Exception
{
System.out.println(solution("karap",2));
}
}