c - 排列字符串以使模式匹配

标签 c string algorithm comparison permutation

问题是计算字符串 B 有多少种排列具有等效模式到更大的字符串 A。例如,如果 A="aabbccd"B="xx",那么它应该打印 3,因为 "aa""bb""cc" > 是 A 的所有子字符串,与 B 具有相同的模式。

我尝试将子字符串作为数字传递,例如 xx 变为 "11" 并对字符串 A 执行相同的操作,但是我仍然无法让它工作。有任何想法吗?长度最大可达 10^7

这是更改模式的代码:

void transform(int* dest, char* original, int len) {
    int j=1;
    Al[original[0]-'a']=j;
    dest[0]=j;
    j++;
    for (int i=1;i<len;i++) {
        if (Al[original[i]-'a']==0) 
            Al[original[i]-'a']=j++;
        dest[i]=Al[original[i]-'a'];
    }
}

最佳答案

概念:使用正则表达式

您需要以下正则表达式(\\w)\\1{(REPETITIONS-1)}
我不了解 C,但 Java 提供了一个库来编译 RegEx 模式。这是一个实现您想要的类:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringPatternPermutation {
    public static void main(String[] args) {
        int REPETITIONS = 3;
        String REGEX = "(\\w)\\1{" + (REPETITIONS-1) + "}";
        String INPUT = "abbbbbbccddeffff";

        Pattern p = Pattern.compile(REGEX);
        Matcher m = p.matcher(INPUT); 

        int count = 0;
        while(m.find()){
            String match = m.group();
            System.out.println(match);
            count++;
        }

        System.out.println(count);
    }
}

这是对上面代码的测试:https://ideone.com/5nztaa
这是一个用于测试任何正则表达式的有用网站:https://regexr.com/

关于c - 排列字符串以使模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49789883/

相关文章:

python - 将看起来像列表的字符串转换为真正的列表 - python

c++ - 我可以从 C++ 字符串中获取非常量 C 字符串吗?

c++ - 如何优化获取数组中的最大值?

java - Java中如何知道两个文本或字符串的相等百分比?

c - 3D 网格的 Morton 逆向编码

c - 函数指针相对于标志的优势

c - C 中的空参数

c - printf ("%d %d %d\n",++a,a++,a) 输出

string - Bash:如何评估这个字符串?

algorithm - 运行解析器时出现 Antlr4 错误