我需要一个 java 程序,它应该从给定的字符串组合中给出所有字典单词。示例:如果给定的字符串是“IOSMNEAB”,它是一个长度为 8 的字符串。我需要 IS、NAME、SOME、SON、MEAN 等单词。
我的解决方案:我对字符串进行了所有排列,并在已经创建的字典数据库中进行了搜索。但它只给出 8 位长度的单词。我需要长度 >=2 和 <=8 的单词。请帮忙 :-(
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Random;
import java.sql.*;
public final class Combination1 {
static String url = "jdbc:mysql://localhost:3306/file";
static int count;
static String Vowel = "AEIOU";
static String Consonant = "BCDFGHJKLMNPQRSTVWXYZ";
static StringBuffer word;
static Connection con;
static ResultSet rs;
static PreparedStatement preparedStatement;
static Random randomGenerator = new Random();
public static final void main(String... aArgs){
String str="";
for(int i=0;i<5;i++){
char a = getRandomConsonant();
str = str+a;}
for(int i=0;i<3;i++){
char a = getRandomVowel();
str = str+a;}
StringBuffer strBuf = new StringBuffer(str);
count = 0;
doPerm(strBuf,str.length());
if(count>=1){
try
{
Class.forName("com.mysql.jdbc.Driver");
try
{
con = DriverManager.getConnection(url,"root","1234");
preparedStatement = con.prepareStatement("insert into FILE.WORDS values (?,?)");
preparedStatement.setString(1, str);
preparedStatement.setInt(2, count);
preparedStatement.executeUpdate();
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
catch(ClassNotFoundException e)
{
System.out.println(e);
}
}
}
private static char getRandomVowel(){
int randomInt = randomGenerator.nextInt(4);
return Vowel.charAt(randomInt);
}
private static char getRandomConsonant(){
int randomInt = randomGenerator.nextInt(20);
return Consonant.charAt(randomInt);
}
private static void swap(StringBuffer str, int pos1, int pos2){
char t1 = str.charAt(pos1);
str.setCharAt(pos1, str.charAt(pos2));
str.setCharAt(pos2, t1);
}
private static void doPerm(StringBuffer str, int index){
if(index == 0)
{
System.out.println(str);
try
{
String word = str.toString();
Class.forName("com.mysql.jdbc.Driver");
try
{
con = DriverManager.getConnection(url,"root","1234");
preparedStatement = con.prepareStatement("SELECT * FROM DICT WHERE word=?");
preparedStatement.setString(1, word);
rs = preparedStatement.executeQuery();
rs = preparedStatement.getResultSet();
if(rs.next()){
count++;
}
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
catch(ClassNotFoundException e)
{
System.out.println(e);
}
}
else {
doPerm(str, index-1);
int currPos = str.length()-index;
for (int i = currPos+1; i < str.length(); i++) {
swap(str,currPos, i);
doPerm(str, index-1);
swap(str,i, currPos);
}
}
}
}