我们定义了一个字母“0123456789abcdefghijklmnopqstuvxzyz”。假设增量从末尾到开头起作用,每个增量将“加”一个字母表的ASCII值:
例如:
"a" will become "b"
"0" will become "1"
"9" will become "a"
"z" will become "0"
"abc" -> "abd"
"01z" -> "020"
..
etc
以下算法将起作用:
class Increment {
private $alphabet;
public function __construct($alphabet)
{
$this->alphabet = $alphabet;
}
public function getNext($text)
{
$length = strlen($text);
$increment = true;
for ($i=$length; $i--; $i > 0) {
$currentCharacter = $text[$i];
if ($increment) {
$increment = $this->hasReachEndOfAlphabet($currentCharacter);
$text[$i] = $this->getIncrementedCharacter($currentCharacter);
}
}
return $text;
}
private function getIncrementedCharacter($currentCharacter)
{
$position = strpos($this->alphabet, $currentCharacter);
if (!$this->hasReachEndOfAlphabet($currentCharacter)) {
return $this->alphabet[++$position];
}
return $this->alphabet[0];
}
private function hasReachEndOfAlphabet($currentCharacter)
{
$position = strpos($this->alphabet, $currentCharacter);
if ($position < strlen($this->alphabet) -1) {
return false;
}
return true;
}
} //end of class
$text = "g67de5c1e86bc123442db60ae9ce615042dbf4e14e7z481ba3c1c9c3219101gh";
$alphabet = "0123456789";
for ($i=97;$i<=122;$i++) {
$alphabet .= chr($i);
}
$increment = new Increment($alphabet);
$next = $increment->getNext($text);
print_r($next.PHP_EOL); // outputs g67de5c1e86bc123442db60ae9ce615042dbf4e14e7z481ba3c1c9c3219101gi