【LeetCode】205 Isomorphic Strings (c++实现)
来源:互联网 发布:淘宝剑三升级代练 编辑:程序博客网 时间:2024/05/01 17:48
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to gett.
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<char, char> m; map<char, char> 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; }};
0 0
- 【LeetCode】205 Isomorphic Strings (c++实现)
- 【LeetCode-205】Isomorphic Strings(C++)
- LeetCode(205)Isomorphic Strings
- leetcode(c++) Isomorphic Strings
- 【leetcode】205. Isomorphic Strings(Python & C++)
- LeetCode 205 - Isomorphic Strings
- [LeetCode 205]Isomorphic Strings
- LeetCode 205-Isomorphic Strings
- leetcode 205: Isomorphic Strings
- leetcode 205 Isomorphic Strings
- LeetCode 205:Isomorphic Strings
- leetcode-205 Isomorphic Strings
- Isomorphic Strings - LeetCode 205
- Isomorphic Strings leetcode 205
- leetcode 205:Isomorphic Strings
- leetcode-205 Isomorphic Strings
- Isomorphic Strings(leetcode 205)
- leetcode[205]:Isomorphic Strings
- 如何查出一台linux服务器上有哪些人在登录
- CommonNext 下步
- Release版本下pthread_mutex_t死锁分析
- 八皇后问题
- linux服务开机启动顺序
- 【LeetCode】205 Isomorphic Strings (c++实现)
- POJ 2947-Widget Factory(高斯消元解同余方程式)
- 【LeetCode】19 Remove Nth Node From End of List (c++实现)
- Andorid 网络状态改变监听不到问题的解决
- 【LeetCode】20 Valid Parentheses (c++实现)
- scrollview 嵌套 viewpager 滑动冲突的解决办法
- python pass (空操作)语句
- 实列3_1
- 新建jenkins-plugin