单词分割

来源:互联网 发布:生活中的人工智能产品 编辑:程序博客网 时间:2024/04/28 20:23
public class AlgTest {
      private static final int START = 0;//开始值
      public static void main(String[] args) {
            String s = "hellleet";
           Set<String> dict = new HashSet<String>();
           dict.add("hell");
           dict.add("leet");
           if (wordBreak(s, dict,START)) {
                   System.out.println("符合");
            }
     }
     public static boolean wordBreak(String s, Set<String> dict, int start){
                return helper(s, dict, start);

      }

    private static boolean helper(String s,Set<String> dict,int start){
        if(start == s.length()){
             return true;//递归回归标记
        }        
        for(String atom : dict){
             int len = atom.length();
             int end = start + len;
             if(end > s.length()){
                     continue;
              }
             if(s.substring(start, end).equals(atom)){
                    if(helper(s, dict, start + len)){//递归
                          return true;
                      }
               }
        }
    return false;
    }
}
0 0
原创粉丝点击