1. 程式人生 > >205. Isomorphic Strings

205. Isomorphic Strings

amp determine other term repl pub ace mine can

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.

判斷一個字符串是否可以替換為另一個字符串

C++(6ms):

 1 class Solution {
 2 public:
 3     bool isIsomorphic(string s, string t) {
 4         vector<int
> map_s(128,0) ; 5 vector<int> map_t(128,0) ; 6 for(int i = 0 ; i < s.size() ; i++){ 7 if(map_s[s[i]] != map_t[t[i]]){ 8 return false ; 9 } 10 map_s[s[i]] = i+1 ; 11 map_t[t[i]] = i+1 ; 12 } 13 return
true ; 14 } 15 };

Java(7ms):

 1 public class Solution {
 2     public boolean isIsomorphic(String s1, String s2) {
 3         int[] m1 = new int[128];
 4         int[] m2 = new int[128];
 5         for (int i = 0; i < s1.length(); i++) {
 6             if (m1[s1.charAt(i)] != m2[s2.charAt(i)]) 
 7                 return false;
 8             m1[s1.charAt(i)] = i+1 ;
 9             m2[s2.charAt(i)] = i+1 ;
10         }
11         return true;
12     }
13 }

205. Isomorphic Strings