题目: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.
one:元素遍历,若s元素在Map里 s元素Map的键不是t元素false;若元素不在Map里在被映射的set里false,否则分别加入Map及set。
public class Solution {
public boolean isIsomorphic(String s, String t) {
if(s==null||t==null){return false;}
if(s.length()!=t.length())return false;
Map<Character,Character> map = new HashMap<Character,Character>();
Set<Character> set = new HashSet<Character>();
for(int i=0;i<s.length();i++){
char c1 = s.charAt(i);
char c2 = t.charAt(i);
if(map.containsKey(c1)){
if(map.get(c1)!=c2) return false;
}else{
if(set.contains(c2))return false;
else{
map.put(c1,c2);
set.add(c2);
}
}
}
return true;
}
}public class Solution {
public boolean isIsomorphic(String s, String t) {
Map m = new HashMap();
for (Integer i=0; i<s.length(); ++i)
if (m.put(s.charAt(i), i) != m.put(t.charAt(i)+"", i))
return false;
return true;
}
}public class Solution {
public boolean isIsomorphic(String sString, String tString) {
char[] s = sString.toCharArray();
char[] t = tString.toCharArray();
int length = s.length;
if(length != t.length) return false;
char[] sm = new char[256];
char[] tm = new char[256];
for(int i=0; i<length; i++){
char sc = s[i];
char tc = t[i];
if(sm[sc] == 0 && tm[tc] == 0){
sm[sc] = tc;
tm[tc] = sc;
}else{
if(sm[sc] != tc || tm[tc] != sc){
return false;
}
}
}
return true;
}
}class Solution { public: bool isIsomorphic(string s, string t) { int m1[256] = {0}, m2[256] = {0}, n = s.size(); for (int i = 0; i < n; ++i) { if (m1[s[i]] != m2[t[i]]) return false; m1[s[i]] = i + 1; m2[t[i]] = i + 1; } return true; } };public boolean isIsomorphic(String s1, String s2) { Map<Character, Integer> m1 = new HashMap<>(); Map<Character, Integer> m2 = new HashMap<>(); for(Integer i = 0; i < s1.length(); i++) { if(m1.put(s1.charAt(i), i) != m2.put(s2.charAt(i), i)) { return false; } } return true; }
本文介绍了一种算法,用于判断两个字符串是否为同构字符串。通过使用HashMap和HashSet,确保所有出现过的字符都被正确映射且不会产生冲突。提供了三种不同的实现方式,包括使用Map进行直接比较的方法。
2139

被折叠的 条评论
为什么被折叠?



