2012-11-12 171 views

回答

0
function findCommonSubstring(s1, s2, n) { 

    s1 = s1.toLowerCase(); 
    s2 = s2.toLowerCase(); 
    var min = s1.length < s2.length ? s1 : s2; 
    var max = min == s1 ? s2 : s1; 

    if(n <= 0 || n > min.length) { 
     return false; 
    } 

    var substring; 
    for(var i=0; i<=min.length-n; i++) { 
     if(max.indexOf((substring = min.substring(i, i+n))) > -1) { 
      return substring; 
     } 
    } 

    return false; 
} 

电话:

alert(findCommonSubstring("California", "Unical", 3));​ 

打印:

cal 

Demo

+0

函数应该考虑到用户使用n <= 0并返回false的场合 – MIrrorMirror

+0

@MIrrorMirror如果用户使用'n <= 0','for'循环根本就不会有任何迭代和函数然后会返回'false'。 – sp00m

+0

谢谢..它工作得很好.. – user1817701

0
function matchStrings(s1, s2, charnum) { 
    var found = false; 
    var i = 0; 
    if (charnum>0 && charnum<s2.length) { 
     s1=s1.toLowerCase(); 
     s2=s2.toLowerCase(); 
     for (i=0; i<=s2.length - charnum; i++) { 
      if (s1.indexOf(s2.substr(i, charnum)) > -1) { 
       found = true; 
       break; 
      } 
     } 
    } 
    return found; 
} 
+0

当'i = 1'时,如果在's1'中找到's2'的第一个字符,该函数返回'true'? – gefei

+0

确实,我很懒。现在更正 – MIrrorMirror

+0

也是错误的。它只检查是否在s1 – gefei

0
function test(first,second,nl) 
{ 
    first=first.toLowerCase(); 
    second=second.toLowerCase(); 

    if(first.length>second.length) 
    { 
     var len=first.length ; 
    } 
    else 
    { 
     var len=second.length; 
     var t=first; 
     first=second; 
     second=t; 
    } 

    //var len=first.length>second.length?first.length:second.length; 

    var count=0; 
    while(len>=nl) 
    { 
     str=first.substr(count,nl); 
     if(second.indexOf(str)!=-1) 
     { 
      return str; 
      break; 
     } 
     count++; 
     len--; 
    } 
    return false;   
} 
alert(test('Cal','unicbbl',4)) 
alert(test('California','unicali',3)); 
alert(test('California','unicali',4)); 
[test here][1] 


    [1]: http://jsfiddle.net/tuMRg/5/ 
+0

混淆解决方案是错误的。这里证明: http://jsfiddle.net/tuMRg/3/尽管事实上两个字符串没有4个字符的公共子字符串,它返回“l”。 – MIrrorMirror

+0

在这种情况下,您必须确定要搜索的字符串以及要搜索的字符串,字符数也应小于要搜索的字符串长度。 –

0

以下是相当复杂,但如果您从大型内容中搜索字符串,这是一个不错的选择。它从筛选可能的匹配开始,然后测试这些可能性。

var atLeastMatch = function(search, content, atLeast) { 
    var search = search, 
     content = content, 
     regex = new RegExp('[' + search + ']{' + atLeast + ',}', "i", "g"), 
     possibleMatches = content.match(regex); 

    for (var i = 0, j = possibleMatches.length; i < j; i++) { 
     if (possibleMatches[i].length > atLeast) { 
      for (var k = 0, l = possibleMatches[i].length - atLeast; k <= l; k++) { 
       if ((new RegExp(possibleMatches[i].slice(k, k + atLeast), "i")).test(search)) { 
        return true; 
       } 

      } 

     } else { 
      if ((new RegExp(possibleMatches[i], "i")).test(search)) { 
       return true; 
      } 

     } 

    } 

    return false; 

} 

console.log(atLeastMatch('California', 'Unical', 3));