Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Subsequence {
- public static void main(String[] args)
- {
- BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
- try{
- String input=br.readLine();
- String res= input.replaceAll("[^a-zA-Z]"," " );
- String[] Alltokens=res.split("\\s+");
- int N=Alltokens.length; //total number of strings in input line
- for(int i=0;i<N;i++) //Alltokens is the input line
- Alltokens[i]=Alltokens[i].toLowerCase();
- int k= Integer.parseInt(br.readLine()); //number of tokens to be searched in sub sequence of input line
- String[] tokens=new String[k];
- for(int i=0;i<k;i++)
- {tokens[i]=br.readLine();
- tokens[i]=tokens[i].toLowerCase();
- }
- boolean found=false; //Flag to indicate if all tokens have been found
- HashSet<String> lookup=new HashSet<String>();
- for (int start=0;start<k;start++)
- {//build a HashSet of first k strings of input line.Minimun set which can contain k different tokens
- lookup.add(Alltokens[start]);
- }
- Collection<String> tok=Arrays.asList(tokens); //collection of tokens to be found
- System.out.println("tokens are "+tok.toString());
- if(lookup.containsAll(tok))
- found=true;
- int minRange=0,maxRange=N; //minimun interval which contains all tokens
- for(int min=0,max=k;min>=0&&max<N;) //Start with first string in input,If tokens are not found.Add kth string in input and test
- {
- if(found==false)
- {while(!lookup.containsAll(tok)&&max<N) //Minimum value of max for which min-max contains tok
- {
- lookup.add(Alltokens[max]);
- System.out.println(" Increasing Max "+lookup.toString()+" found ="+found);
- max++
- }//close while
- if(max<N)
- found=true;
- else
- {found=false; //if all tokens not found in [0-N)
- System.out.print("No subsegment found");
- System.exit(0);
- }
- } //Close outer If found==false
- else
- { //If all tokens were found in 0-max ,strip off string[0] and test and so on for next min which would be 1
- lookup.remove(Alltokens[min]);
- min++;
- if(!lookup.containsAll(tok)) //Strip of min from the range min-max and test min+1 to max
- found=false;
- System.out.println(" Increasing Min "+lookup.toString()+" found = "+found);
- }//close else
- if(max-min<maxRange-minRange&&found==true)
- {minRange=min;
- maxRange=max;
- }
- } //Close for loop
- if(found==true)
- System.out.print(minRange+" "+maxRange);
- } //Close try block
- catch(IOException e){}
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement