1

I have been doing some Leetcode problems. And i found this particular solution for this problem. I understood all of it except this line m[s1.charAt(i)] = m[s2.charAt(i)+256] = i+1; If someone can explain me this that would be really helpful. Thanks!

Question

Given two strings s and t, determine if they are isomorphic.

Two strings s and t are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.

Example 1:

Input: s = "egg", t = "add" Output: true

Example 2:

Input: s = "foo", t = "bar" Output: false

Example 3:

Input: s = "paper", t = "title" Output: true

Solution

public class Solution {
    public boolean isIsomorphic(String s1, String s2) {
        int[] m = new int[512];
        for (int i = 0; i < s1.length(); i++) {
            if (m[s1.charAt(i)] != m[s2.charAt(i)+256]) return false;
            m[s1.charAt(i)] = m[s2.charAt(i)+256] = i+1;
        }
        return true;
    }
}
  • 3
    Does this answer your question? [Can't understand purpose of a = b = 0;](https://stackoverflow.com/questions/33139757/cant-understand-purpose-of-a-b-0) – TYeung Aug 28 '21 at 16:45

1 Answers1

3

So, in a nutshell doing:

m[s1.charAt(i)] = m[s2.charAt(i)+256] = i+1;

Is the same as doing:

m[s1.charAt(i)] = i+1;
m[s2.charAt(i)+256] = i+1;

So if I have:

int i = 20;
int y = 10;
i = y = 5;

System.out.println(i);
System.out.println(y);

The output is:

5
5
FORGISDELUXE
  • 103
  • 1
  • 6
  • Oh and i was thinking its something like `m[s1.charAt(i)] = m[s2.charAt(i)+256]` and `m[s2.charAt(i)+256] = i+1;`. Thanks for clearing my doubt! – Saurav Shrivastav Aug 28 '21 at 15:58
  • 1
    @SauravShrivastav To expand, `a = b = c;` is parsed as `a = (b = c);`; the expression `b = c` affects the value of `c` to `b`, and evaluates to that value; then `a = ...` is evaluated and affects that value to `a`. – Stef Aug 28 '21 at 20:04
  • 1
    @SauravShrivastav In general, when looking at a complex expression that does more than one thing, you have to imagine that there are extra parentheses; and if you know where these parentheses are, you can understand the expression. For instance, `a && b || c` is equivalent to `(a && b) || c`, and `a + b * c` is equivalent to `a + (b * c)`; similarly, `a = b = c` is equivalent to `a = (b = c)`. – Stef Aug 28 '21 at 20:08