在Java中以不同方式拆分单词。

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

breaking down words in different ways in java

问题

我想要以不同的方式创建随字符串而来的单词,具体如下。我不确定如何最好地实现这一点。

输入:Paul Thomas Anderson

输出:Paul Thomas Anderson,P Thomas Anderson,T Anderson,Paul T Anderson,Paul Thomas A,T Anderson,Paul A,Pa Anderson ...

在Java中,最佳且通用的方法是什么?

英文:

I want to create words that come with a string in different ways as follows. I'm not sure how best to do this

input: Paul Thomas Anderson

output: Paul Thomas Anderson, P Thomas Anderson, T Anderson, Paul T Anderson, Paul Thomas A, T Anderson, Paul A, Pa Anderson ...

What would be the best and generic method to do this in java?

答案1

得分: 0

理想情况下,你会希望展示一下你目前为止尝试过的内容。话虽如此,你所写的要求基本如下:

  • 将一个句子分解为每个单词
  • 生成一个答案元组,由每个单词的组合和/或每个单词的前k个字母组成。

实际上,当你写下 Paul Thomas Anderson 时,你处理的是 k = 单词长度 的特殊情况。

你的答案可能与Java无关,我认为你可能在软件工程Stack Exchange或编程Stack Exchange网站上能得到更好的帮助。

从以下方式开始:

List<List<String>> result = new ArrayList<List<String>>();
String[] words = seed.split(" "); // 这将给出每个单词
for (String word : words){
   for (int i = 1; i < word.length(); i++){
     String part = word.substring(0,i); // 确保 length-1 实际上是正确的最大值
     // 在这里进行保存 - 你需要一个良好的数据结构 - 不确定我的List of List 是否合适
   }
}

实际上,你应该参考此帖子中关于集合的笛卡尔积。这将极大地简化你需要做的事情。

英文:

Ideally, you'd want to show what you've tried so far. That being said, the requirement you wrote is essentially as follows:

  • take a sentence and break it into each of its words
  • generate a tuple of answers made up of a combination of each word and/or the first k letters of each word.

In fact, when you write Paul Thomas Anderson, you're handling the special case where k = length(word).

Your answer is probably not going to be specific to Java and I think you might be better served in the software engineering Stack Exchange or the Programming Stack Exchange sites.

Start with something along the lines of:

List&lt;List&lt;String&gt;&gt;() result = new ArrayList&lt;List&lt;String&gt;&gt;();
String[] words = seed.split(&quot; &quot;); // this will give you each word
for (String word : words){
   for (int i = 1; i &lt; word.length(); i++){
     String part = word.substring(0,i); // make sure length-1 is actually the right max
     // Do the saving here - you need a good structure - not sure my List of List cuts it
   }
}

Actually you should refer to this post for the cartesian product of your sets. This will simplify greatly what you need to do.

huangapple
  • 本文由 发表于 2020年9月12日 00:44:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63851144.html
匿名

发表评论

匿名网友

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

确定