如何在java中搜索所有可能组合的字符串? [英] How to search string with all possible combination in java?

查看:70
本文介绍了如何在java中搜索所有可能组合的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何像Android studio一样在Java中实现与给定键的所有可能组合的字符串匹配. 可以吗?任何可用的正则表达式模式.

How to implement string matching with all possible combination of given key in Java just like Android studio. does? Any regex pattern available.

推荐答案

您不需要为此使用正则表达式,因为 贪心算法可以.

You do not need a regex for this, because a greedy algorithm will do.

您可以在 O(n+p) 中将字符串与模式匹配,其中 n 是字符串的长度,p 是模式的长度,遵循一个非常简单的策略:对于模式的每个字符,查找字符串中从当前索引开始的匹配字符.如果找到匹配项,将索引向前推进,然后从模式中查找下一个字符.如果模式在字符串结束前耗尽,则匹配;否则,您没有匹配项.

You can match a string against a pattern in O(n+p), where n is the length of string and p is the length of pattern, by following a very simple strategy: for each character of the pattern, look for a matching character in the string starting at the current index. If you find a match, advance the index past it, and look for the next character from the pattern. If the pattern gets exhausted before end of string, you have a match; otherwise, you do not have a match.

public static boolean match(String s, String p) {
    String us = s.toUpperCase();
    int i = 0;
    for (char c : p.toUpperCase().toCharArray()) {
        int next = us.indexOf(c, i);
        if (next < 0) {
            return false;
        }
        i = next+1;
    }
    return true;
}

演示.

这篇关于如何在java中搜索所有可能组合的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆