Easy understand solution using hashCode() and equals()


  • 0
    class Element
        {
            int multiFactor = 123;
            char[] arr = null;
            int Len = 0;
            Element(String str)
            {
                if(str != null)
                {
                    if(str.length() != 0)
                    {
                        arr = str.toCharArray();
    					Len = arr.length;
                    }
                }
            }
            public int hashCode()
            {
                if(arr == null) return 0;
                if(Len == 0) return -1;
                if(Len == 1) return -2;
                multiFactor = 123;
                int hash = Len*multiFactor;
                for(int i = 1; i < Len; i++,multiFactor++)
                {
                    int diff = arr[i] - arr[i-1];
                    if(arr[i] < arr[i-1])
                        diff = 26 + diff;
                    hash += multiFactor*diff;
                }
                return hash;
            }
            public boolean equals(Object e)
            {
    			if(!(e instanceof Element))
    				return false;
    			Element ee = (Element)e;
                return this.hashCode() == ee.hashCode();
            }
        }
    

Log in to reply
 

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