2012-09-19 29 views

回答

3

以下Java代码解决了从字符串中检测重复项的问题。如果重复单词由换行符或标点符号分隔,则不应该有任何问题。

String duplicatePattern = "(?i)\\b(\\w+)\\b[\\w\\W]*\\b\\1\\b"; 
    Pattern p = Pattern.compile(duplicatePattern); 
    String phrase = "this is#$;%@;<>?|\\` p is a is Test\n of duplicate test"; 
    Matcher m = p.matcher(phrase); 
    String val = null; 
    while (m.find()) { 
     val = m.group(); 
     System.out.println("Matching segment is \"" + val + "\""); 
     System.out.println("Duplicate word: " + m.group(1)+ "\n"); 
    } 

代码的输出将是:

Matching segment is "is#$;%@;<>?|\` p is a is" 
Duplicate word: is 

Matching segment is "Test 
of duplicate test" 
Duplicate word: Test 

这里,m.group(1)语句表示针对模式的第一组匹配的字符串[这里,是(\\ W +)] 。

+3

你的意思是他回答了他自己的问题...... – Borgleader

+0

这个规模有多好? –

+0

@BrianAgnew如果对于某些边缘测试用例的代码有任何问题,请通知我。 –

8

用正则表达式可以做的最好的事情是O(N^2)搜索的复杂度。通过将输入分成单词并使用HashSet来检测重复项,您可以轻松实现时间和空间搜索的复杂性。

+1

然后,由于您需要用于检测的后备数据结构,因此再折衷是时间vs空间 – gtgaxiola

+1

是,但正如我所说的,空间开销是'O(N)';即与输入的大小成正比。 –

+0

@StephenC但你能提供任何显示O(N^2)时间复杂度的链接吗?因为这个链接声称它是O(N)。 http://stackoverflow.com/questions/5892115/whats-the-time-complexity-of-average-regex-algorithms –

相关问题