Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.

Return all such possible sentences.  For example, given s = “catsanddog”, dict = [“cat”, “cats”, “and”, “sand”, “dog”].  A solution is [“cats and dog”, “cat sand dog”]. 

 

One of the raw solution:

 

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Solution {

public static void main(String cp[])
{
wordBreak();
}

public static void wordBreak() {
// Note: The Solution object is instantiated only once and is reused by each test case.
String s;
Set<String> s1=new HashSet<String>();
s1.add(“cat”);
s1.add(“cats”);
s1.add(“and”);
s1.add(“sand”);
s1.add(“dog”);
System.out.println(“Enter a String”);
Scanner in=new Scanner(System.in);
s=in.nextLine();
int slength=s.length()/2;
String[] afterbreak=s.split(“”);
int size=afterbreak.length;
System.out.println(“Breaked string is “);
// for(String o:afterbreak)
// {
// System.out.println(o);
// }
StringBuilder t=new StringBuilder();
ArrayList<String> fs=new ArrayList<String>();

for(int i=0;i<size/2+1;i++)
{

for(String m:s1)
{

System.out.println(“Value of t is now “+t);
boolean m1=m.equalsIgnoreCase(t.toString());
if(m1)
{
System.out.println(“Entered into if loop “);
fs.add(t.toString());

}//end of if

}//end of inner for loop

t.append(afterbreak[i]);

}//end of outer for loop

System.out.println(“Contents of Matched set are “);
for(String m:fs)
{
System.out.println(m);
}

}
}

Advertisements

About qainterviews

Software Geek,QA Expert,Blogger
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s