finding common prefix of array of strings

后端 未结 17 1661
一向
一向 2020-11-29 06:15

I have an array like this:

$sports = array(
\'Softball - Counties\',
\'Softball - Eastern\',
\'Softball - North Harbour\',
\'Softball - South\',
\'Softball -         


        
17条回答
  •  情歌与酒
    2020-11-29 06:50

    Here's an elegant, recursive implementation in JavaScript:

    function prefix(strings) {
        switch (strings.length) {
    
          case 0:
            return "";
    
          case 1:
            return strings[0];
    
          case 2:
            // compute the prefix between the two strings
            var a = strings[0],
                b = strings[1],
                n = Math.min(a.length, b.length),
                i = 0;
            while (i < n && a.charAt(i) === b.charAt(i))
                ++i;
            return a.substring(0, i);
    
          default:
            // return the common prefix of the first string,
            // and the common prefix of the rest of the strings
            return prefix([ strings[0], prefix(strings.slice(1)) ]);
        }
    }
    

提交回复
热议问题