205. Isomorphic Strings(字符串同构)

逃离我推掉我的手 2021-12-21 10:21 307阅读 0赞

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.

Example 1:

  1. Input: s = "egg", t = "add"
  2. Output: true

Example 2:

  1. Input: s = "foo", t = "bar"
  2. Output: false

Example 3:

  1. Input: s = "paper", t = "title"
  2. Output: true
  3. 解释:就是像以前语文题的 aabb 开开心心和快快乐乐就是字符同构。
  4. 方法一:记录摆放位置
  5. public boolean isIsomorphic(String s, String t) {
  6. int[] preIndexOfS = new int[256];
  7. int[] preIndexOfT = new int[256];
  8. for (int i = 0; i < s.length(); i++) {
  9. char sc = s.charAt(i), tc = t.charAt(i);
  10. if (preIndexOfS[sc] != preIndexOfT[tc]) {
  11. return false;
  12. }
  13. preIndexOfS[sc] = i + 1;
  14. preIndexOfT[tc] = i + 1;
  15. }
  16. return true;
  17. }

方法二:用hashMap记录对应关系

  1. public class Solution {
  2. public boolean isIsomorphic(String s, String t) {
  3. HashMap<Character,Character> map=new HashMap<Character,Character>();
  4. for(int i=0;i<s.length();i++){
  5. char a=s.charAt(i),b=t.charAt(i);
  6. if(map.containsKey(a)){
  7. if(map.get(a)!=b){
  8. return false;
  9. }
  10. }else{
  11. if(!map.containsValue(b)){
  12. map.put(a,b);
  13. }else{
  14. return false;
  15. }
  16. }
  17. }
  18. return true;
  19. }
  20. }

转载于:https://www.cnblogs.com/shaer/p/10847361.html

发表评论

表情:
评论列表 (有 0 条评论,307人围观)

还没有评论,来说两句吧...

相关阅读