PHP and hash


  • 0
    T

    In PHP, and probably other languages, you've got the hash function. And there's this lossy little algorithm called "adler32" which gives you an 8 character string. Useful for this kinda thing. For eaxmple

    <?php
    class Codec {
        private $table = [];
        
        public function encode($url) {
            $hash = hash("adler32", $url, false);
            
            // To prevent storing one url multiple times, we only store it if it's not already stored
            // In PHP it doesn't matter, keys can be rewritten and we don't really need to check,
            // but if we were connected to a DB...
            if (!isset($this->table[$hash])) $this->table[$hash] = $url;
            
            return $hash;
        }
        
        public function decode($hash) {
            // Always make sure that the hash has already been stored
            if (isset($this->table[$hash])) return $this->table[$hash];
            else return "";
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.