Find longest common prefix?

前端 未结 9 1904
忘掉有多难
忘掉有多难 2020-12-10 03:50

In two strings:

\"Mary Had a Little Lamb\"
\"Mary Had a Big Lamb\"

should return

\"Mary Had a \"

9条回答
  •  渐次进展
    2020-12-10 04:10

    Apache Commons to the rescue!

    org.apache.commons.lang3.StringUtils.getCommonPrefix

    ... and compare the source code with the ingenious/valiant effort of dyross here (currently with highest vote). But her/his code, good though it is, only handles two Strings. This can handle any number.

    Apart from not re-inventing the wheel, I can think of two reasons why using Apache Commons is always best for this sort of thing.

    1. The Apache engineers can be counted on to have developed comprehensively tested code which deals with any gotchas
    2. It means you don't clutter up your beautiful code with stoopid utility methods. Instead you can get on with the, um, interesting things.

    If the whole of a given Apache Commons module is really too much for your context (they're usually just a few kB, but OK) you can extract the bits you need from the source code (assuming this complies with the licence). In this case indexOfDifference is an essential function...

提交回复
热议问题