2010-09-08 3 views
4

У меня есть строка длиной около тысячи символов, состоящая из L's, T's и A. Я уверен, что в нем есть простой шаблон, и мне интересно, есть ли быстрый и простой способ найти его. Эта строка изменяется, так что это не просто один.Распознавание шаблона Java String

Узор Я ищу, например, если строка была

LLLLLLLLAATAALLLLALLLLLLAATAALLLATLLLLLAATAALLAALLLLLAATAALL 

подстрока LLLLLAATAALL повторы 4 раза в этой строке. Я хочу найти подстроки вроде этого, но я не знаю, где они начинаются, заканчиваются, сколько их есть и как долго они находятся в основной строке.

Если в Java есть какие-либо инструменты для поиска таких вещей, любой совет будет очень благодарен.

нт

+0

Это своего рода проблема ИИ для меня, когда вы не знаете шаблон и хотите найти. Я думаю, что для ограниченной строки вы можете найти множество шаблонов, единственная проблема заключается в том, сколько из них будет правильным в следующей строке – vodkhang

+0

Это в значительной степени стандартная проблема компьютерной науки. См. Http://en.wikipedia.org/wiki/Longest_repeated_substring_problem и http://www.cs.duke.edu/csed/algoprobs/substring.html – joschi

+0

Эта проблема, хотя и проста, действительно интригует меня! Какую инопланетную передачу вы перехватили? (-) Вы просто ищете повторяющиеся подстроки? Я могу представить себе другие, более сложные шаблоны. Во всяком случае, я сейчас изучаю решения и отправлю ответ, если найду что-нибудь полезное. –

ответ

3

Хорошо, поэтому я взял код от here и адаптировал его для отслеживания и печати самой длинной повторяющейся подстроки. Просто запустите его с помощью JUnit.

/* Copyright (c) 2010 the authors listed at the following URL, and/or 
the authors of referenced articles or incorporated external code: 
http://en.literateprograms.org/Suffix_tree_(Java)?action=history&offset=2010

Permission is hereby granted, free of charge, to any person obtaining 
a copy of this software and associated documentation files (the 
"Software"), to deal in the Software without restriction, including 
without limitation the rights to use, copy, modify, merge, publish, 
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject to 
the following conditions: 

The above copyright notice and this permission notice shall be 
included in all copies or substantial portions of the Software. 

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 

Retrieved from: http://en.literateprograms.org/Suffix_tree_(Java)?oldid=16641 
*/ 

import java.util.ArrayList; 
import java.util.Collection; 
import java.util.List; 
import org.junit.Test; 

public class SuffixTree { 
    @Test 
    public void sampleUsage() { 

     AbstractSuffixTree tree = new SimpleSuffixTree(
       "LLLLLLLLAATAALLLLALLLLLLAATAALLLATLLLLLAATAALLAALLLLLAATAALL"); 
     System.out.println("Longest repeating substring " 
       + tree.best.printResult() + " repetitions=" + tree.best.visits 
       + " length=" + tree.best.stringDepth); 
    } 
} 

abstract class AbstractSuffixTree { 

    SuffixTreeNode best; 
    String text = null; 
    SuffixTreeNode root = null; 
    int inputAlphabetSize = -1; 

    AbstractSuffixTree(String text) { 
     if (text.length() > 0 && text.charAt(text.length() - 1) == '$') { 
      this.text = text; 
     } else { 
      this.text = text + "$"; 
     } 
    } 

} 

class SimpleSuffixTree extends AbstractSuffixTree { 

    public SimpleSuffixTree(String text) { 
     super(text); 
     constructTree(); 
    } 

    private void constructTree() { 
     super.root = new SuffixTreeNode(this); 
     best = root; 
     char[] s = super.text.toCharArray(); 
     for (int i = 0; i < s.length; i++) { 
      List<String> suffixList = new ArrayList<String>(); 
      for (int k = i; k < s.length; k++) { 
       suffixList.add(s[k] + ""); 
      } 
      super.root.addSuffix(suffixList, i + 1); 
     } 
    } 

} 

class CompactSuffixTree extends AbstractSuffixTree { 

    public CompactSuffixTree(SimpleSuffixTree simpleSuffixTree) { 
     super(simpleSuffixTree.text); 
     super.root = compactNodes(simpleSuffixTree.root, 0); 
     super.best = simpleSuffixTree.best; 
    } 

    private SuffixTreeNode compactNodes(SuffixTreeNode node, int nodeDepth) { 
     node.nodeDepth = nodeDepth; 
     for (SuffixTreeNode child : node.children) { 
      while (child.children.size() == 1) { 
       SuffixTreeNode grandchild = child.children.iterator().next(); 
       child.incomingEdge.label += ", " 
         + grandchild.incomingEdge.label; 
       child.stringDepth += grandchild.incomingEdge.label.length(); 
       child.children = grandchild.children; 
       // for (SuffixTreeNode grandchild : child.children) 
       grandchild.parent = node; 
      } 
      child = compactNodes(child, nodeDepth + 1); 
     } 
     return node; 
    } 

} 

class SuffixTreeNode { 

    AbstractSuffixTree tree; 
    SuffixTreeEdge incomingEdge = null; 
    int nodeDepth = -1; 
    int label = -1; 
    Collection<SuffixTreeNode> children = null; 
    SuffixTreeNode parent = null; 
    int stringDepth; 
    int id = 0; 
    public static int c; 
    public int visits = 1; 

    public SuffixTreeNode(AbstractSuffixTree tree, SuffixTreeNode parent, 
      String incomingLabel, int depth, int label, int id) { 
     children = new ArrayList<SuffixTreeNode>(); 
     incomingEdge = new SuffixTreeEdge(incomingLabel, label); 
     nodeDepth = depth; 
     this.label = label; 
     this.parent = parent; 
     stringDepth = parent.stringDepth + incomingLabel.length(); 
     this.id = id; 
     this.tree = tree; 
    } 

    public SuffixTreeNode(AbstractSuffixTree tree) { 
     children = new ArrayList<SuffixTreeNode>(); 
     nodeDepth = 0; 
     label = 0; 
     this.tree = tree; 
    } 

    public void addSuffix(List<String> suffix, int pathIndex) { 
     SuffixTreeNode insertAt = this; 
     insertAt = search(this, suffix); 
     insert(insertAt, suffix, pathIndex); 
    } 

    private SuffixTreeNode search(SuffixTreeNode startNode, List<String> suffix) { 
     if (suffix.isEmpty()) { 
      throw new IllegalArgumentException(
        "Empty suffix. Probably no valid simple suffix tree exists for the input."); 
     } 
     Collection<SuffixTreeNode> children = startNode.children; 
     for (SuffixTreeNode child : children) { 
      if (child.incomingEdge.label.equals(suffix.get(0))) { 
       suffix.remove(0); 
       child.visits++; 
       if (child.visits > 1 
         && child.stringDepth > tree.best.stringDepth) { 
        tree.best = child; 
       } 
       if (suffix.isEmpty()) { 
        return child; 
       } 
       return search(child, suffix); 
      } 
     } 
     return startNode; 
    } 

    private void insert(SuffixTreeNode insertAt, List<String> suffix, 
      int pathIndex) { 
     for (String x : suffix) { 
      SuffixTreeNode child = new SuffixTreeNode(tree, insertAt, x, 
        insertAt.nodeDepth + 1, pathIndex, id); 
      insertAt.children.add(child); 
      insertAt = child; 
     } 
    } 

    public String toString() { 
     StringBuilder result = new StringBuilder(); 
     String incomingLabel = this.isRoot() ? "" : this.incomingEdge.label; 
     for (int i = 1; i <= this.nodeDepth; i++) 
      result.append("\t"); 
     if (this.isRoot()) { 
      c = 1; 
      this.id = 1; 
     } else { 
      this.id = c; 
      result.append(this.parent.id + " -> "); 
      result.append(this.id + "[label=\"" + incomingLabel + "\"]" + "(" 
        + visits + "," + (stringDepth) + ")" + ";\n"); 
     } 
     for (SuffixTreeNode child : children) { 
      c++; 
      child.id = c; 
      result.append(child.toString()); 
     } 
     return result.toString(); 
    } 

    public String printResult() { 
     if (parent == null) { 
      return ""; 
     } else { 
      return this.parent.printResult() + this.incomingEdge.label; 
     } 
    } 

    public boolean isRoot() { 
     return this.parent == null; 
    } 

    public boolean isLeaf() { 
     return children.size() == 0; 
    } 

} 

class SuffixTreeEdge { 

    String label = null; 
    @SuppressWarnings("unused") 
    private int branchIndex = -1; 

    public SuffixTreeEdge(String label, int branchIndex) { 
     this.label = label; 
     this.branchIndex = branchIndex; 
    } 

} 

Выходные:

Серия повторяющихся подстроки LLLLLLAATAALLL повторы = 2 длина = 14

EDIT: ответ на ваши комментарии.

В настоящее время я просто отслеживаю самый длинный повторяющийся SuffixTreeNode (это поле в AbstractSuffixTree). Вы можете изменить это, чтобы отслеживать SortedQueue узлов, упорядоченных по их stringDepth.

+0

thx много. это почти делает то, что им нужно. единственное, заключается в том, что я не ищу самую длинную повторяющуюся подстроку. когда я использовал его на фактическом TestString 1000 символов, он вернулся что-то вроде: «LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL» – nite

+1

его, возможно, что струна им смотрю на самый длинный, а также он не может быть. я havent глубоко рассмотрел код, который вы предоставили, но есть ли способ поиска второго, самого длинного, третьего и т. д.? – nite

-1

вы получите представление о том, как сделать это с помощью следующего кода считать строку «привет»;

общественного INT countHi (String ул) {

Количество INT = 0, г = str.length() - 1; String goal = "hi";

для (Int J = 0; J < я; j ++) { , если (str.substring (J, J + 2) .equals (цель)) счета ++;} возврата рассчитывать; }

+2

Привет, Jinjavajin, я не знаю, как искать солнечный столб в строке. Проблема в том, что я не знаю какую подстроку я ищу. Поэтому что-то вроде указания «цели» будет работать только после того, как я узнаю, что такое шаблон. – nite

+2

ваш фрагмент кода показывает ужасную грубую силу, которая не является хорошей идеей, когда у вас есть тысячи персонажей и неизвестный цели – Gaim

Смежные вопросы