首页 > 其他 > 详细

Isomorphic Strings

时间:2016-05-11 09:32:33      阅读:268      评论:0      收藏: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.

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.

思路:没有必要使用HashMap。 只需要建立两个数组,用于记录字符串s 和 字符串t 中 的每一个字符 到目前为止出现的位置(位于字符串中的位置)即可。对于同一个下标的字符判断其上一次出现时位于字符串中的位置是否相同,如果不相同则不是Isomorphic.如果遍历完整个字符串长度仍然符合条件则为isomophic.

 1 public class Solution {
 2     public boolean isIsomorphic(String s, String t) {
 3         if (s.length() != t.length()) {
 4             return false;
 5         }
 6         int[] a = new int[256];
 7         int[] b = new int[256];
 8         for (int i = 0; i < s.length(); i++) {
 9             if (a[(int)s.charAt(i)] != b[(int)t.charAt(i)]) {
10                 return false;
11             } else {
12                 a[(int)s.charAt(i)]  = i + 1;
13                 b[(int)t.charAt(i)]  = i + 1;
14             }
15         }
16         return true;
17     }
18 }

 

Isomorphic Strings

原文:http://www.cnblogs.com/FLAGyuri/p/5480576.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!