15 June 2018

search on dictionary

Given an input string and a dictionary of words, find out if the input string can be segmented into a space-separated sequence of dictionary words. See following examples for more details.
Consider the following dictionary 
{ i, like, sam, sung, samsung, mobile, ice, 
  cream, icecream, man, go, mango}

Input:  ilike
Output: Yes 
The string can be segmented as "i like".

Input:  ilikesamsung
Output: Yes
The string can be segmented as "i like samsung" 
or "i like sam sung".<>

public class NewClass27 {
      void print(String k,String res)
      {
          if(k.equals(res))
          {
              System.out.println("yes");
          }else
          {
              System.out.println("No");
          }
      }
      int dictionary(String ar[],String a)
      {
          int k=0;
          for(int i=0;i<ar.length;i++)
          {
              if(ar[i].equals(a))
              {
                
                   k=1; 
              }
          }return k;
      }
    String search(String k,String ar[])
    {    String temp="",result="";
          int t;
        for(int i=0;i<k.length();i++)
        {
            for(int j=k.length();j>=i+1;j--)
            {
                temp=k.substring(i,j);
                t=dictionary(ar,temp);
                if(t==1)
                {
                    result+=temp;
                    i=j-1;
                    break;
                }
            }
        }return result;
    }

    public static void main(String args[])
    {
            String dic[]={"i","like","sam","sung","samsung","mobile","ice",
  "cream","icecream","man","go","mango"};
            String k="ilikemangogomanice";
            String result="";
            NewClass27 ob=new NewClass27();
            result=ob.search(k, dic);
            ob.print(k,result);
    }
}


No comments:

Post a Comment