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.

此题目有时间限制,关键是如何优化时间。

我开始的做法是两个for循环,那么时间复杂度就是n的平方,但是它有一个测试用例,两个字符串特别长,于是就出现了“Time Limit Exceeded”。代码如下:

class Solution {

public:

 bool isIsomorphic(string s, string t) {
int len = s.length();
// 时间复杂度n平方,不满足题目要求。
for (size_t i = ; i < len; i++) {
for (size_t j = i + ; j < s.length(); j++) {
if ((s[i] == s[j] && t[i] != t[j]) || (s[i] != s[j] && t[i] == t[j])) {
return false;
}
}
}
return true;
}
};

上面的方法不行,那就必须要减少时间复杂度,最后我想了一个方法:使用一个<char, char>的map映射,for循环两个入参的每一个char,如果发现对应关系改变了,那么就说明两个字符串不是isomorphic的了。时间复杂度为O(n),代码如下:

class Solution {
public:
bool isIsomorphic(string s, string t) {
int len = s.length();
map<char, char> m;
map<char, char> m2;
for (size_t i = ; i < len; i++) {
if (m.find(s[i]) == m.end()) {
m[s[i]] = t[i];
}else if (m[s[i]] != t[i]) {
return false;
}
if (m2.find(t[i]) == m2.end()) {
m2[t[i]] = s[i];
}else if (m2[t[i]] != s[i]) {
return false;
}
}
return true;
}
};

最新文章

  1. js返回顶部效果
  2. ARC-数据类型需要释放的情况
  3. 让DIV中的内容水平和垂直居中
  4. 理解 %IOWAIT (%WIO)
  5. OpenJudge计算概论-循环移动
  6. B. Rebranding
  7. UIKit Animation
  8. 7.微软AJAX的解决方案
  9. PHP 一维数组排序
  10. sql查询每门课程成绩最高的学生
  11. 解决:Visual Assist X 不支持HTML、Javascript等提示
  12. java 内省
  13. 获取访问者IP
  14. UVA-1572
  15. C# 使用 protobuf 进行对象序列化与反序列化
  16. html 手机web超出屏幕宽度的内容不换行,并产生横向滚动条
  17. PAT乙级1002
  18. Python基础系列讲解——TCP协议的socket编程
  19. EBS增加客制应用CUX:Custom Application
  20. 基于SSM框架配置多数据源

热门文章

  1. RedRabbit——基于BrokerPattern服务器框架
  2. 架构模式之REST架构
  3. 【工作代码】复杂 JSON 值替换处理
  4. 图解 &amp; 深入浅出Java初始化与清理:构造器必知必会
  5. 【redmine】密码忘了后重新设置
  6. Mobilize.Net Silverlight bridge to Windows 10 UWP
  7. MySQL降权:MySQL以Guests帐户启动设置方法
  8. Windows 10 Weather App无法正常显示解决方法
  9. Linux高级编程--04.GDB调试程序(查看数据)
  10. 【HTML】Iframe中的onload事件