205. Isomorphic Strings

来源:互联网 发布:5轴激光切割编程软件 编辑:程序博客网 时间:2024/05/22 03:40

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.

Subscribe to see which companies asked this question

其实用HashMap就好,可惜当年刚开始写不知道这玩意啊……就是每读一个s字母,就去找相对应的t中的字母,如果没找到就存起来,找到了就和已经存的比较,有冲突就报错就好。

public class Solution {<span style="white-space:pre"></span>public boolean isIsomorphic(String s, String t) {<span style="white-space:pre"></span>int[] a = new int[200];<span style="white-space:pre"></span>int[] b = new int[200];<span style="white-space:pre"></span>int s1 = 0;<span style="white-space:pre"></span>int s2 = 0;<span style="white-space:pre"></span>for (s1 = 0; s1 < s.length(); s1++) {<span style="white-space:pre"></span>if (a[s.charAt(s1) - ' '] == 0) {<span style="white-space:pre"></span>a[s.charAt(s1) - ' '] = t.charAt(s1) - ' ';<span style="white-space:pre"></span>continue;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>if (a[s.charAt(s1) - ' '] != t.charAt(s1) - ' ')<span style="white-space:pre"></span>return false;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>for (s1 = 0; s1 < t.length(); s1++) {<span style="white-space:pre"></span>if (b[t.charAt(s1) - ' '] == 0) {<span style="white-space:pre"></span>b[t.charAt(s1) - ' '] = s.charAt(s1) - ' ';<span style="white-space:pre"></span>continue;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>if (b[t.charAt(s1) - ' '] != s.charAt(s1) - ' ')<span style="white-space:pre"></span>return false;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>return true;<span style="white-space:pre"></span>}}

0 0
原创粉丝点击