LeetCode -- Isomorphic Strings

Source: Internet
Author: User

LeetCode -- Isomorphic Strings
Description:
Given two strings s and t, determine if they are isomorphic.


Two strings 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.


For example,
Given egg, add, return true.


Given foo, bar, return false.


Given paper, title, return true.


Note:
You may assume both s and t have the same length.


Returns the homogeneous string. That is, the new string obtained after each character is replaced by the same character and the length of the two strings is the same. Such a string is a homogeneous string.




Ideas:
Returns false if the length is not equal.
Two hash tables, hash1 and has2. Hash1: record the position of the last occurrence of the current character while traversing the first string.
If hash1 contains s [I], then hash2 must also contain t [I] And hash1 [s [I] (s [I] the last position where it appears) it must also be equal to the last position where hash2 [t [I] (t [I] appears ).
If hash1 does not contain s [I], then hash2 must not contain t [I].


Implementation Code:




public class Solution {    public bool IsIsomorphic(string s, string t) {        var hash1 = new Dictionary
 
  ();var hash2 = new Dictionary
  
   ();for(var i = 0;i < s.Length; i++){if(!hash1.ContainsKey(s[i])){hash1.Add(s[i], i);if(hash2.ContainsKey(t[i])){return false;}hash2.Add(t[i],i);}else{if(!hash2.ContainsKey(t[i]) || hash2[t[i]] != hash1[s[i]]){return false;}hash1[s[i]] = i;hash2[t[i]] = i;}}return true;    }}
  
 


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.