Advertisement
sweet1cris

Untitled

Feb 9th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.16 KB | None | 0 0
  1.  
  2. public class Solution {
  3.     /**
  4.      * @param s a string
  5.      * @param t a string
  6.      * @return true if the characters in s can be replaced to get t or false
  7.      */
  8.     public boolean isIsomorphic(String s, String t) {
  9.         // Write your code here
  10.         int[] m1 = new int[128];
  11.         int[] m2 = new int[128];
  12.         for (int i = 0; i < s.length(); ++i) {
  13.             int cs = (int) s.charAt(i);
  14.             int ts = (int) t.charAt(i);
  15.             if (m1[cs] == 0 && m2[ts] == 0) {
  16.                 m1[cs] = ts;
  17.                 m2[ts] = 1;
  18.             } else if (m1[cs] != ts) {
  19.                 return false;
  20.             }
  21.         }
  22.         return true;
  23.     }
  24. }
  25.  
  26. // version: 高频题班
  27. public class Solution {
  28.     /**
  29.      * @param s a string
  30.      * @param t a string
  31.      * @return true if the characters in s can be replaced to get t or false
  32.      */
  33.     public boolean isIsomorphic(String s, String t) {
  34.         // Write your code here
  35.         int[] map = new int[256];  // ASCII 的范围是0-255
  36.         char[] sc = s.toCharArray();
  37.         char[] tc = t.toCharArray();
  38.  
  39.         for (int i = 0; i < s.length(); i++) {
  40.             if (map[sc[i]] == 0) {
  41.                 map[sc[i]] = tc[i];
  42.             } else {
  43.                 if (map[sc[i]] != tc[i]) {
  44.                     return false;
  45.                 }
  46.             }
  47.         }
  48.  
  49.         /*
  50.         ///////////////////////////////假设t的取值只有'a' - 'z' 时做t->s 映射的一种写法   (仅做演示使用)
  51.         int[] map2 = new int[26];
  52.         for (int i = 0; i < t.length(); i++) {
  53.             if (map2[tc[i] - 'a'] == 0) {
  54.                 map2[tc[i] - 'a'] = sc[i];
  55.             } else {
  56.                 if (map2[tc[i] - 'a'] != sc[i]) {
  57.                     return false;
  58.                 }
  59.             }
  60.         }
  61.         */
  62.  
  63.         int[] map2 = new int[256];
  64.         for (int i = 0; i < t.length(); i++) {
  65.             if (map2[tc[i]] == 0) {
  66.                 map2[tc[i]] = sc[i];
  67.             } else {
  68.                 if (map2[tc[i]] != sc[i]) {
  69.                     return false;
  70.                 }
  71.             }
  72.         }
  73.  
  74.         return true;
  75.     }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement