[LeetCode] Isomorphic Strings, leetcodeisomorphic

Source: Internet
Author: User

[LeetCode] Isomorphic Strings, leetcodeisomorphic

 

Given two stringsSAndT, Determine if they are isomorphic.

Two strings are isomorphic if the characters inSCan be replaced to getT.

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.

 

I personally think this is an interesting question. First, you must understand what it is called lsomorphic strings. Summarize its features.

In fact, the letters can be different, but the structure must be the same. That is to say, for string s, the index of the duplicate letter must be the same as the string t, and the index of the duplicate letter must be the same and the number is the same.

You can use if statement to write and judge the statement.

The Code is as follows .~

 

public class Solution {    public boolean isIsomorphic(String s, String t) {        if(s.length()!=t.length()) return false;        HashMap<Character,Integer> smap=new HashMap<>();        HashMap<Character,Integer> tmap=new HashMap<>();        for(int i=0;i<s.length();i++){            if(!smap.containsKey(s.charAt(i))){                if(tmap.containsKey(t.charAt(i))){                    return false;                }            }else{                int index=smap.get(s.charAt(i));                if(!tmap.containsKey(t.charAt(i))||tmap.get(t.charAt(i))!=index){                    return false;                }            }            smap.put(s.charAt(i),i);            tmap.put(t.charAt(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.