Isomorphic Strings
来源:互联网 发布:计划表软件 编辑:程序博客网 时间:2024/04/29 09:23
题目名称
Isomorphic Strings—LeetCode链接
描述
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.
分析
分析两个字符串是否是同构的,其实也就是对于s和t中的每个字符之间是否存在一个一一对应关系,所以会用到容器中的map。这里有两个思路:
- 是找到s->t的对应关系,然后寻找t->s的对应关系,如果这两个关系都存在,则返回true,否则返回false。简单点就是 s<->t 等价于 s->t && t->s.
- 用一个set容器,用来存放出现s[i]->t[i]中的t[i],如果下次搜索过程中发现s[j]->t[i],出现t中的一个字符对应了s中的多个字符,则返回false;遍历完整个字符串都没有发现,则返回true。
以下代码采用的是第一种思路。
C++代码
class Solution {public: bool isIsomorphic(string s, string t) { if(s.size()!=t.size()) return false; int length = s.size(); map<char,char> s_t; set<char> unique_t; for(int i=0;i<length;i++){ char c1=s[i]; char c2=t[i]; if(s_t.find(c1)!=s_t.end()){ if(s_t[c1]!=c2) return false; } else{ if(unique_t.find(c2)!=unique_t.end()) return false; else{ s_t[c1]=c2; unique_t.insert(c2); } } } return true; }};
总结
这道题用到了C++容器中的map和set,由于我刚开始学习C++,所以希望这个题目之后能系统学习一下C++的容器。然后我之前在Leetcode还遇到一个类似的题目Word Pattern,大家可以练练手。
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Linux中网络字节序和主机字节序
- 【转】linearLayout 和 relativeLayout的属性区别
- 支持向量机SVM(二)
- ubuntu14.04 修改键盘映射 CapsLock->Ctrl
- swift 2.0 元组
- Isomorphic Strings
- 视频大集合
- 《C算法》笔记12:2-3-4树
- 隐藏具体实现
- Binary Tree Paths
- Vollery框架请求网络去除Header中的IF-MODIFIED-SINCE头标签
- linux常用命令
- hadoop1.2.1在linux中配置安装独立运行Standalone Operation,伪分布Pseudo-Distributed Operation,集群配置三种配置和测试
- arcgis 地理数据库解析(一)