PROBLEM:
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.
SOLVE:
class Solution {
public:
bool isIsomorphic(string s,string t){
int n=s.size();
int index[2][256]={0};
for(int i=0;i<n;i++){
if(index[0][s[i]]!=index[1][t[i]])
return false;
index[0][s[i]]=i+1;
index[1][t[i]]=i+1;
}
return true;
}
};分析:s和t同时遍历,同时判断s或t在之前有没有出现过,如果都出现过且出现的位置相同则ok;否则就输出false。
本文介绍了一种判断两个字符串是否为同构字符串的有效算法。通过同时遍历两个字符串并检查字符映射的一致性来实现,确保所有字符的替换遵循相同的规则。
345

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



