博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
205 Isomorphic Strings
阅读量:4677 次
发布时间:2019-06-09

本文共 1697 字,大约阅读时间需要 5 分钟。

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 = 0; i < len; i++) {       for (size_t j = i + 1; 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
m; map
m2; for (size_t i = 0; 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; }};

转载于:https://www.cnblogs.com/styshoo/p/4625809.html

你可能感兴趣的文章
006 输入和输出
查看>>
Python3.5.2中的变量介绍
查看>>
请比较throw 合throws的区别
查看>>
Python3 的列表
查看>>
javaee 第14周
查看>>
iOS上的MapKit
查看>>
「提离职」算正确的加薪姿势么?
查看>>
最简单的C# Windows服务程序
查看>>
Linux下配置VNC
查看>>
hbase权威指南学习笔记--架构--存储
查看>>
禁用SettingSyncHost.exe
查看>>
Unity 镜子效果
查看>>
MVC
查看>>
OpenCart框架运行流程介绍
查看>>
webstorm使用技巧
查看>>
4273_NOIP2015模拟10.28B组_圣章-精灵使的魔法语
查看>>
简单的验证码识别之Tess4j
查看>>
day1 联合权值
查看>>
BigData07_08 异常Exception
查看>>
CSS兼容IE6,IE7,FF的技巧
查看>>