题目: Strings Homomorphism
public class Solution {
/**
* @param s a string
* @param t a string
* @return true if the characters in s can be replaced to get t or false
*/
public boolean isIsomorphic(String s, String t) {
// Write your code here
if(s == null && t == null) return true;
else if(s == null || t == null) return false;
else if(s.length() != t.length()) return false;
else{
String s1 = "";
String s2 = "";
int j = 0;
for(int i = 0; i < s.length(); i++){
int dis1 = s.indexOf(s.charAt(i));
if(i == dis1){
s1 += j;
j++;
}
else{
s1 += s1.charAt(dis1);
}
}
int l = 0;
for(int k = 0; k < t.length(); k++){
int dis2 = t.indexOf(t.charAt(k));
if(k == dis2){
s2 += l;
l++;
}
else{
s2 += s2.charAt(dis2);
}
}
boolean flag = s1.equals(s2);
return flag;
}
}
}
还有另外一个 题目: First Position Unique Character
public class Solution {
/*
* @param s: a string
* @return: it's index
*/
public int firstUniqChar(String s) {
// write your code here
if (s == null) {
return -1;
}
boolean flag = false;
int i = 0;
for (; i < s.length() - 1; i++) {
String myStr = s.substring(0, i) + s.substring(i + 1);
String ch = Character.toString(s.charAt(i));
if (myStr.contains(ch)) {
continue;
}
else {
flag = true;
break;
}
}
if (flag) {
return i;
}
else {
return -1;
}
}
}
1
LxExExl 2017-09-11 01:14:49 +08:00 via iPhone
第一题不需要 for 循环 长度一样就 true 了吧
第二题 naive 的做法也应该是弄个 hashset O(N) 吧 |
2
RecursiveG 2017-09-11 08:44:09 +08:00
给楼主一个 Strings Homomorphism 的测试样例,
然后建议楼主自己研究下为啥不对。 new Solution().isIsomorphic("abcdefghijkla","abcdefghijkll") |