如何检查字母是否在字符串中?
这是一个很难问的问题,但我会尝试。 我有 4 个字母 m
u
g
o
。我还有免费的字符串单词(s)。
比方说:og
ogg
muogss
。我正在寻找任何明智的方法来检查我是否可以仅使用我的字母构建单词(s)。请注意,我们使用过一次g
,我们将无法再次使用它。
og - possible because we need only **g** and **o**
ogg - not possible we took **o** and **g**, need the second **g**
muogss - not possible we took all, need also additional **s**
所以我的策略是将我的字母放入字符数组中并一一删除,然后检查还剩下多少个来构建单词(s)。但是否可以在几行中使用某种方式,我不知道 - 正则表达式?
It quite hard question to ask but I will try.
I have my 4 letters m
u
g
o
. I have also free string word(s).
Let'say: og
ogg
muogss
. I am looking for any wise method to check if I can construct word(s) using only my letters. Please take notice that we used once g
we won't be able to use it again.
og - possible because we need only **g** and **o**
ogg - not possible we took **o** and **g**, need the second **g**
muogss - not possible we took all, need also additional **s**
So my tactic is take my letters to char array and remove one by one and check how many left to build the word(s). But is it possible to use somehow in few lines, i do not know - regex ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你的方法只有几行...
your method is only a few lines...
这是一个简单的方法:
对于源单词,创建一个大小为 26 的数组,并用它来计算每个字母出现的次数。
对字典中的每个单词执行相同的操作。
然后比较两者。
如果每个字母在字典单词中出现的次数少于或等于源单词的次数,则可以使用它来组成该单词。如果没有,那就不能。
C-Sharpish 伪代码:(可能不会按编写的方式编译)
Here's a simple approach:
For your source word, create an array of size 26 and use it to count the how many times each letter appears.
Do the same for each word in your dictionary.
Then compare the two.
If every letter occurs less than or equal to as many times in the dictionary word as the source word, then it can be used to make that word. If not, then it cannot.
C-Sharpish Pseudocode: (probably doesn't compile as written)
如果您对单词的定义是可用字符的任意排列,那么为什么需要正则表达式?只要确保每个字符都使用一次即可。正则表达式不知道什么是“正确的单词”,最好避免算法使用无效字符,而不是使用它们并使用正则表达式来确保您没有使用无效字符不要使用它们。
If your definition of words is any arbitrary permutation of the available charactters then why do you need a regex? Just make sure you use each characters once. Regex doesn't know what a "correct word" is, and it's better to avoid using invalid characters by your algorithms than using them AND using a regex to make sure you didn't use them.