Comment detail

文字列リストをTRIE Optimizeされた正規表現に (Nested Flatten)
とりあえず素朴に。例題データ読ませると「^program(?:|(?:ist(?:|ic)|m(?:a(?:|(?:r|ti(?:c(?:|ally)|st)))|er)))$」を吐きます。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System;
using System.Collections.Generic;
using System.IO;
static class Program {
    public static void Main(String[] args) {
        // 行ごとに読み込んで
        List<string> words = new List<string>();
        using(StreamReader sr = new StreamReader(args[0])) {
            foreach(string line in sr.ReadToEnd().Split('\n', '\r')) {
                if (line != string.Empty && !words.Contains(line)) {
                    words.Add(line);
                }
            }
            words.Sort();
        }
        // 重複文字数をチェックして
        List<int> indexes = new List<int>(); {
            int[] itemp = new int[words.Count];
            for(int i = words.Count - 1; 1 <= i; i--) {
                int to = Math.Min(words[i - 1].Length, words[i].Length);
                for(int j = 0; j < to && words[i - 1][j] == words[i][j]; j++) {
                    itemp[i]++;
                }
            }
            indexes.AddRange(itemp);
        }
        // 重複文字数を多い順に並び替えて
        List<int> times = new List<int>(); {
            foreach(int cnt in indexes) {
                if (!times.Contains(cnt))
                    times.Add(cnt);
            }
            times.Sort();
            times.Reverse();
        }
        // 重複部分を削っていく
        foreach(int steps in times) {
            for(int i = words.Count - 1; 0 < i; i--) {
                if (indexes[i] == steps) {
                    words[i - 1] = string.Format("{0}(?:{1}|{2})",
                        words[i - 1].Substring(0, steps),
                        words[i - 1].Substring(steps),
                        words[i].Substring(steps));
                    words.RemoveAt(i);
                    indexes.RemoveAt(i);
                }
            }
        }
        string result = "^" + words[0] + "$";
        Console.WriteLine(result);
    }
}
#4259 の指摘を受けて、とりあえず Regex.Escape 挟んでみました。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
--- trie.cs.old Tue Nov 20 01:20:52 2007
+++ trie.cs     Tue Nov 20 01:21:24 2007
@@ -8,7 +8,7 @@
         using(StreamReader sr = new StreamReader(args[0])) {
             foreach(string line in sr.ReadToEnd().Split('\n', '\r')) {
                 if (line != string.Empty && !words.Contains(line)) {
-                    words.Add(line);
+                    words.Add(System.Text.RegularExpressions.Regex.Escape(line)
);
                 }
             }
             words.Sort();

Index

Feed

Other

Link

Pathtraq

loading...