Created
August 5, 2014 06:26
-
-
Save KodeSeeker/63b2a6d8c75595c4064f to your computer and use it in GitHub Desktop.
Longest length of Equal number of "*" and "#" in a string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public int longestLength(String in) | |
| { | |
| char[] chars = in.tocharArray(); | |
| int [] aux= new int[chars.length]; | |
| //create aux array | |
| aux[0]=(chars[0]=='*'?+1:-1); //+1 for * and -1 for #. | |
| int val=aux[0]; | |
| for (int i=1;i<chars.length;i++) | |
| { | |
| if(chars[i]=="*") | |
| { | |
| aux[i]=aux[i-1]+1; | |
| } | |
| if(chars[i]=="#") | |
| { | |
| aux[i]=aux[i-1]-1; | |
| } | |
| } | |
| // now we have to find the longest sequence so far. | |
| //Using a map to find the 'remember ' the longest sequence so far. | |
| HashMap<Integer,Integer> map= new HashMap<Integer,Integer>();//aux[i],i | |
| int max_dist=0; | |
| for (int i=0;i<aux.length;i++) | |
| { | |
| if(i==0) | |
| max_dist=i; | |
| if(map.contains(aux[i])) | |
| max_dist=Math.max(max_dist,i- map.get(aux[i])-1); | |
| else | |
| map.put(aux[i],i); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment