leetcode_Isomorphic Strings

描述:

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.

思路:

题目的大意是用s中字母对应的字母可以组成t中的串,简而言之,就是s中的字母对应在t中的字母是唯一的,而t中的字母对应在s中也是唯一的,问题解决。

代码:

public boolean isIsomorphic(String s, String t) {
        if(s==null)
            return true;
        int len=s.length();
        if(len==1)
            return true;
        boolean flag=true;
        flag=isIso(s, t);//the letter in s must correspond to a unique letter in t
        if(flag)
        	flag=isIso(t, s);//also,the letter in t must correspond to a unique letter in s
        return flag;
    }
	public boolean isIso(String s, String t)
	{
		int len=s.length();
		char arr[]=new char[257];
		Arrays.fill(arr, '%');
        char ch_s,ch_t,temp;
        for(int i=0;i<len;i++)
        {
            ch_s=s.charAt(i);
            ch_t=t.charAt(i);
            if(arr[ch_s]!='%')//judge if ch_s has already appeared or not
            {
                temp=arr[ch_s];
                if(temp!=ch_t)//if  has appeared but the only ch_s corresponded to different alpha
                    return false;
            }else
            	arr[ch_s]=ch_t;
        }
        return true;
	}


你可能感兴趣的:(isomorphic,strings)