如何在字符串模式值birdantantcatbirdcat中获得字符串结果。

huangapple go评论81阅读模式
英文:

How can i get String result in stringPattern value birdantantcatbirdcat

问题

我有一个名为dataDic的数组 { "ant", "bird", "cat" }。

dataDic是我想要在stringPattern上搜索的单词数组。

我想使用dataDic从stringPattern = birdantantcatbirdcat 中获取单词结果。

示例1:
dataDic = { "ant", "bird", "cat" }
答案是 { bird, ant, ant, cat, bird, cat }

示例2:
dataDic = { "ant", "cat" }
答案是 { ant, ant, cat, cat }

这是我的代码:

private static String stringTest = "birdantantcatbirdcat";
private static List<String> dicListWord;
private static List<String> resultString = new ArrayList<>();

public static void main(String[] args) {

    dicListWord = new ArrayList<>();
    dicListWord.add("ant");
    dicListWord.add("bird");
    dicListWord.add("cat");
    String[] data = stringTest.split("");

    for (String dataDic : dicListWord) {
        String[] wordList = dataDic.split("");
        String foundWord = "";
        for (String charTec : data) {
            for (String dicWord : wordList) {
                if (charTec.equals(dicWord)) {
                    foundWord = foundWord.concat(charTec);
                    if (dataDic.equals(foundWord)) {
                        resultString.add(foundWord);
                        foundWord = "";
                    }
                }
            }
        }
    }

    for (String w1 : data) {
        for (String result : resultString) {
            System.out.println(result);
        }
    }
}

运行结果如下:

{ ant, ant, bird, bird, ant, ant, bird, bird, ant, ant, bird, bird, ant, ant, bird, bird, ant, ant, bird, bird, ant, ant, bird, bird, ant, ant, bird, bird, ant, ant, bird, bird, ant, ant, bird, bird, ant, ant, bird, bird, ant, ant, bird, bird, ant, ant, bird, bird, ant, ant, bird, bird, ant, ant, bird, bird, ant, ant, bird, bird, ant, ant, bird, bird, ant, ant, bird, bird }

英文:

i have dataDic that is an array {"ant","bird","cat"}

dataDic is array of word that i want to search on stringPattern

I want to use dataDic to get word result from stringPattern = birdantantcatbirdcat

Ex1.
dataDic = {"ant","bird","cat"}
answer is {bird,ant,ant,cat,bird,cat}
Ex2.
dataDic = {"ant","cat"}
answer is {ant,ant,cat,cat}

this is my code
`private static String stringTest="birdantantcatbirdcat";
private static List<String> dicListWord;
private static List<String>resultString = new ArrayList<>();

public static void main(String[] args) {

    dicListWord = new ArrayList&lt;&gt;();
    dicListWord.add(&quot;ant&quot;);
    dicListWord.add(&quot;bird&quot;);
    dicListWord.add(&quot;cat&quot;);
    String[] data = stringTest.split(&quot;&quot;);

    for (String dataDic:dicListWord) {
        String [] wordList = dataDic.split(&quot;&quot;);
        String foundWord = &quot;&quot;;
        for (String charTec:data) {
            for (String dicWord:wordList) {
                if(charTec.equals(dicWord)){
                    foundWord = foundWord.concat(charTec);
                    if(dataDic.equals(foundWord)){
                        resultString.add(foundWord);
                        foundWord = &quot;&quot;;
                    }
                }
            }
        }
    }

    for (String w1:data) {
        for (String result:resultString) {
                System.out.println(result);
        }
    }
}`

///////////////////////////////////////////////////////////////////////////////

and Result that i run is

{ant,ant,bird,bird,ant,ant,bird,bird,ant,ant,bird,bird,ant,ant,bird,bird,ant,antbird,bird,ant,ant,bird,bird,ant,ant,bird,bird,ant,ant,bird,bird,ant,ant,bird,bird,ant,ant,bird,bird,ant,ant,bird,bird,ant,ant,bird,bird,ant,ant,bird,bird,ant,ant,bird,bird,ant,ant,bird,bird,ant,ant,bird,bird,ant,ant,bird,bird,ant,ant,bird,bird,ant,ant,bird,bird,ant,ant,bird,bird}

答案1

得分: 0

这是一个单词拆分问题,可以使用深度优先搜索进行解决。但在进行深度优先搜索之前,最好先检查给定的字符串模式是否可以被拆分,以便在情况下能够获得更好的运行时,特别是当给定一个在字典中找不到匹配单词的长字符串模式时。

public class P00140_Word_Break_II {
    public static void main(String[] args) {
        String input = "catsanddog";
        List<String> wordDict = Arrays.asList("cat", "cats", "and", "sand", "dog");
        P00140_Word_Break_II solution = new P00140_Word_Break_II();
        List<String> results = solution.wordBreak(input, wordDict);
        System.out.println(results);
        
        String input1 = "birdantantcatbirdcat";
        List<String> wordDict1 = Arrays.asList("ant", "bird", "cat");
        List<String> results1 = solution.wordBreak(input1, wordDict1);
        System.out.println(results1);
    }

    public List<String> wordBreak(String s, List<String> wordDict) {
        Set<String> dict = new HashSet<>(wordDict);
        List<String> result = new ArrayList<>();
        if (s == null || s.length() == 0 || !isbreakable(s, dict)) {
            return result;
        }
        helper(s, 0, new StringBuilder(), dict, result);
        return result;
    }

    public void helper(String s, int start, StringBuilder item, Set<String> dict, List<String> results) {
        if (start >= s.length()) {
            results.add(item.toString());
            return;
        }

        if (start != 0) {
            item.append(" ");
        }

        for (int i = start; i < s.length(); i++) {
            String temp = s.substring(start, i + 1);
            if (dict.contains(temp)) {
                item.append(temp);
                helper(s, i + 1, item, dict, results);
                item.delete(item.length() + start - i - 1, item.length());
            }
        }
        if (start != 0) {
            item.deleteCharAt(item.length() - 1);
        }
    }

    private boolean isbreakable(String s, Set<String> dict) {
        boolean[] dp = new boolean[s.length() + 1];
        dp[0] = true;
        for (int i = 1; i <= s.length(); i++) {
            for (int j = 0; j < i; j++) {
                String subString = s.substring(j, i);
                if (dp[j] && dict.contains(subString)) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.length()];
    }
}
英文:

This is a word break problem and can be solved using a depth-first search. But it is wise to check before if the given string pattern is breakable or not to get better run-time in scenario where we have given a long string pattern that doesn't match any words in the dictionary.

public class P00140_Word_Break_II {
public static void main(String[] args) {
String input = &quot;catsanddog&quot;;
List&lt;String&gt; wordDict = Arrays.asList(&quot;cat&quot;, &quot;cats&quot;, &quot;and&quot;, &quot;sand&quot;, &quot;dog&quot;);
P00140_Word_Break_II solution = new P00140_Word_Break_II();
List&lt;String&gt; results = solution.wordBreak(input, wordDict);
System.out.println(results);
String input1 = &quot;birdantantcatbirdcat&quot;;
List&lt;String&gt; wordDict1 = Arrays.asList(&quot;ant&quot;,&quot;bird&quot;,&quot;cat&quot;);
List&lt;String&gt; results1 = solution.wordBreak(input1, wordDict1);
System.out.println(results1);
}
public List&lt;String&gt; wordBreak(String s, List&lt;String&gt; wordDict) {
Set&lt;String&gt; dict = new HashSet&lt;&gt;(wordDict);
List&lt;String&gt; result = new ArrayList&lt;&gt;();
if (s == null || s.length() == 0 || !isbreakable(s, dict)) {
return result;
}
helper(s, 0, new StringBuilder(), dict, result);
return result;
}
public void helper(String s, int start, StringBuilder item, Set&lt;String&gt; dict, List&lt;String&gt; results) {
if (start &gt;= s.length()) {
results.add(item.toString());
return;
}
if (start != 0) {
item.append(&quot; &quot;);
}
for (int i = start; i &lt; s.length(); i++) {
String temp = s.substring(start, i + 1);
if (dict.contains(temp)) {
item.append(temp);
helper(s , i+1 , item , dict , results);
item.delete(item.length() + start - i - 1 , item.length());
}
}
if(start!=0) item.deleteCharAt(item.length()-1);
}
private boolean isbreakable(String s, Set&lt;String&gt; dict) {
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for (int i = 1; i &lt;= s.length(); i++) {
for (int j = 0; j &lt; i; j++) {
String subString = s.substring(j, i);
if (dp[j] &amp;&amp; dict.contains(subString)) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}

}

答案2

得分: 0

使用TreeMap来存储单词的位置作为键,单词本身作为值,当您在字符串中导航以查找单词的匹配项时。您需要选择TreeMap的原因是它按其键的自然顺序排序,这对于您的要求非常重要。

您的要求指出,结果列表中的单词应按照它们在字符串中出现的顺序排列。

演示:

import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<String> words = List.of("ant", "bird", "cat");
        String str = "birdantantcatbirdcat";
        System.out.println(getMatchingWords(words, str));
    }

    static List<String> getMatchingWords(List<String> words, String str) {
        Map<Integer, String> map = new TreeMap<Integer, String>();
        for (String word : words) {
            Pattern pattern = Pattern.compile(word);
            Matcher matcher = pattern.matcher(str);
            while (matcher.find()) {
                map.put(matcher.start(), matcher.group());
            }
        }
        return map.values().stream().collect(Collectors.toList());
    }
}

输出:

[bird, ant, ant, cat, bird, cat]
英文:

Use a TreeMap to store the position of a word as the key and the word itself as the value as you navigate the string to find matches for the word. The reason why you need to choose a TreeMap is that it is sorted according to the natural ordering of its keys which is an important aspect for your requirement.

Your requirement states that the words in the resulting list should be in the order of their occurrences in the string.

Demo:

import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List&lt;String&gt; words = List.of(&quot;ant&quot;, &quot;bird&quot;, &quot;cat&quot;);
String str = &quot;birdantantcatbirdcat&quot;;
System.out.println(getMatchingWords(words, str));
}
static List&lt;String&gt; getMatchingWords(List&lt;String&gt; words, String str) {
Map&lt;Integer, String&gt; map = new TreeMap&lt;Integer, String&gt;();
for (String word : words) {
Pattern pattern = Pattern.compile(word);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
map.put(matcher.start(), matcher.group());
}
}
return map.values().stream().collect(Collectors.toList());
}
}

Output:

[bird, ant, ant, cat, bird, cat]

huangapple
  • 本文由 发表于 2020年4月8日 23:21:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/61104221.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定