Return a new string that sorts between two given strings

前端 未结 3 1282
抹茶落季
抹茶落季 2020-12-09 11:59

Given two strings a and b, where a is lexicographically < b, I\'d like to return a string c such that a < c < b. The use case is inserting a node in a database sort

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 12:17

    This is a very simple way to achieve this and probably far from optimal (depending on what you call optimal of course).

    I use only a and b. I suppose you could generalise this to use more letters.

    Two simple observations:

    1. Creating a new string that comes after another string is easy: just append one or more letters. E.g., abba < abbab.
    2. Creating a new string that comes before another string x is only always guaranteed to be possible if x ends with b. Now, replace that b by an a and append one or more letters. E.g., abbab > abbaab.

    The algorithm is now very simple. Start with a and b as sentinels. Inserting a new key between two existing keys x and y:

    • If x is a prefix of y: the new key is y with the ending b replaced by ab.
    • If x is not a prefix of y: the new key is x with a b appended.

    Example run:

    a, b
    a, ab*, b
    a, aab*, ab, b
    a, aab, ab, abb*, b
    a, aab, ab, abab*, abb, b
    a, aaab*, aab, ab, abab, abb, b
    

提交回复
热议问题