205. Isomorphic Strings (同构字符串判断)

野性酷女 2022-07-15 01:22 239阅读 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.

  1. import java.util.Hashtable;
  2. public class Solution {
  3. char index = 'a';
  4. public boolean isIsomorphic(String s, String t) {
  5. Map<Character,Character> table = new Hashtable<Character, Character>();
  6. StringBuilder sb = new StringBuilder();
  7. for(char ch:s.toCharArray()){
  8. if(table.get(ch)==null){
  9. table.put(ch, index++);
  10. }
  11. sb.append(table.get(ch));
  12. }System.out.println(sb.toString());
  13. table.clear();
  14. index='a';
  15. int pos=0;
  16. for(char ch:t.toCharArray()){
  17. if(table.get(ch)==null){
  18. table.put(ch, index++);
  19. }
  20. if(table.get(ch)!=sb.charAt(pos++)){
  21. return false;}
  22. }return true;
  23. }
  24. }

发表评论

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

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

相关阅读