Ex6_4 利用动态规划算法判断一个字符串是否由有效的单词组成,若是则输出单词序列,算法的运行时间不超过n的平方

 1 //利用动态规划算法判断一个字符串是否由有效的单词组成,若是则输出单词序列,算法的运行时间不超过n的平方
 2 public class Ex6_4 {
 3 
 4     private static Set<String> wordSet;
 5     
 6     public static void main(String[] args) {
 7         // TODO Auto-generated method stub
 8         wordSet=new HashSet<>();
 9         wordSet.add("it");
10         wordSet.add("was");
11         wordSet.add("the");
12         wordSet.add("algorithoms");
13         wordSet.add("best");
14         wordSet.add("is");
15         wordSet.add("of");
16         wordSet.add("times");
17         wordSet.add("interesting");
18         wordSet.add("good");
19         String strs1=" itwasthebestoftimesgood"; 
20         checkWord(strs1);     //true:it was the best of times good 
21         
22         String strs2=" algorithomsisinteresting";
23         checkWord(strs2);     //true:algorithoms is interesting 
24         
25         String strs3=" thisisastring";
26         checkWord(strs3);    //false:
27     }
28     
29     public static void checkWord(String strs){
30         boolean[] vi=new boolean[strs.length()];            //记录前i个字符组成的子串能否分割成有效的单词
31         vi[0]=true;
32         
33         int[] index=new int[strs.length()];                  //记录以该下标为终点的合法单词的起始位置
34         index[0]=-1;                                      //不能构成合法单词
35 
36         
37         for(int i=1;i<=strs.length()-1;i++){              //判断前i+1个字符组成的子串能否分割成有效的单词
38             for(int j=i-1;j>=0;j--){
39                 String strTemp=strs.substring(j+1,i+1);   
40                 if(vi[j] && isAWord(strTemp)){
41                     vi[i]=true;
42                     index[i]=j+1;
43                     break;
44                 }
45                 else{
46                     vi[i]=false;
47                     index[i]=-1;
48                 }
49             }
50             
51         }//外for
52     
53     //打印出单词序列
54         System.out.print(vi[strs.length()-1]+":");
55         if(vi[strs.length()-1]){
56             String words="";
57             int b=strs.length()-1;
58             int a=index[b];
59             while(a!=-1){
60                 words=strs.substring(a,b+1)+" "+words;
61                 b=a-1;
62                 a=index[b];
63             }
64             System.out.println(words);
65         }
66         
67     }
68     
69     //判断单词是否合法
70     public static boolean isAWord(String str){
71         if(wordSet.contains(str))
72             return true;
73         return false;
74     }
75 }
View Code

 

posted @ 2017-10-28 20:42  清风☆薰衣草  阅读(145)  评论(0)    收藏  举报