Skip to content

Instantly share code, notes, and snippets.

@KodeSeeker
Created August 5, 2014 06:26
Show Gist options
  • Select an option

  • Save KodeSeeker/63b2a6d8c75595c4064f to your computer and use it in GitHub Desktop.

Select an option

Save KodeSeeker/63b2a6d8c75595c4064f to your computer and use it in GitHub Desktop.
Longest length of Equal number of "*" and "#" in a string.
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