fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <array>
  4. #include <limits>
  5.  
  6. bool IsIsomorphic(std::string const &s, std::string const &t)
  7. {
  8. std::array<char, std::numeric_limits<char>::max() - std::numeric_limits<char>::min() + 1> arr = {};
  9.  
  10. for (size_t i = 0, n = s.length(); i < n; ++i)
  11. {
  12. size_t pos = static_cast<size_t>(s[i]);
  13.  
  14. if (arr[pos] == 0)
  15. {
  16. arr[pos] = t[i];
  17. continue;
  18. }
  19.  
  20. if (arr[pos] != t[i])
  21. return false;
  22. }
  23.  
  24. return true;
  25. }
  26.  
  27. int main()
  28. {
  29. // test
  30. std::string const ss[10][2] =
  31. {
  32. { "add", "egg" },
  33. { "foo", "bar" },
  34. { "paper", "title" },
  35. { "aab", "xyz" },
  36. { "aab", "xxy" },
  37. { "abcd", "aabb" },
  38. { "aaba", "bbaa" },
  39. { "bbaa", "aaba" },
  40. { "topcode", "topcoat" },
  41. { "topcoat", "topcode" }
  42. };
  43.  
  44. for (auto const &s : ss)
  45. std::cout
  46. << "\"" << s[0] << "\""
  47. << (IsIsomorphic(s[0], s[1]) ? " is isomorphic to " : " is NOT isomorphic to ")
  48. << "\"" << s[1] << "\"" << std::endl;
  49.  
  50. return 0;
  51. }
Success #stdin #stdout 0s 4280KB
stdin
Standard input is empty
stdout
"add" is isomorphic to "egg"
"foo" is NOT isomorphic to "bar"
"paper" is isomorphic to "title"
"aab" is NOT isomorphic to "xyz"
"aab" is isomorphic to "xxy"
"abcd" is isomorphic to "aabb"
"aaba" is NOT isomorphic to "bbaa"
"bbaa" is NOT isomorphic to "aaba"
"topcode" is isomorphic to "topcoat"
"topcoat" is NOT isomorphic to "topcode"