My accepted c++ solution, 12ms, easy understand.


  • 1

    Use two vectors as flag to record the offset of each character in string s and t. The range of offset is -255 to 255, so we can set a value outside the range as the initial value, and in the following code, it is 1000.

    class Solution  {
    public:
        bool isIsomorphic(std::string s, std::string t) {
    		std::string::size_type len1 = s.size(), len2 = t.size();
    		if (len1 != len2)
    			return false;
    		std::vector<int> flag1(256, 1000), flag2(256, 1000);
    		for (std::string::size_type i = 0; i != len1; ++i) {
    			int pos1 = s[i] + 128, pos2 = t[i] + 128, dif = s[i] - t[i];
    			if (flag1[pos1] == 1000)
    				flag1[pos1] = dif;
    			else if (flag1[pos1] != dif)
    				return false;
    			if (flag2[pos2] == 1000)
    				flag2[pos2] = dif;
    			else if (flag2[pos2] != dif)
    				return false;
    		}
    		return true;
        }
    };
    

    or

    class Solution {
    public:
        bool isIsomorphic(std::string s, std::string t) {
    		std::string::size_type len1 = s.size(), len2 = t.size();
    		if (len1 != len2)
    			return false;
    		std::vector<int> flag(512, 1000);
    		for (std::string::size_type i = 0; i != len1; ++i) {
    			int pos1 = s[i] + 128, pos2 = t[i] + 384, dif = s[i] - t[i];
    			if (flag[pos1] == 1000)
    				flag[pos1] = dif;
    			else if (flag[pos1] != dif)
    				return false;
    			if (flag[pos2] == 1000)
    				flag[pos2] = dif;
    			else if (flag[pos2] != dif)
    				return false;
    		}
    		return true;
        }
    };

Log in to reply
 

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