简体   繁体   English

检查给定的两个字符串是否同构

[英]Check if the two given String are Isomorphic

I am working on the LeetCode problem Isomorphic Strings :我正在研究 LeetCode 问题 Isomorphic Strings

Given two strings s and t , determine if they are isomorphic.给定两个字符串st ,确定它们是否同构。

Two strings s and t are isomorphic if the characters in s can be replaced to get t .如果s中的字符可以替换为t ,则两个字符串st是同构的。

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.没有两个字符可以 map 到同一个字符,但是一个字符可以 map 到它自己。

Example 1:示例 1:

 Input: s = "egg", t = "add" Output: true

Example 2:示例 2:

 Input: s = "foo", t = "bar" Output: false

Example 3:示例 3:

 Input: s = "paper", t = "title" Output: true

Constraints:约束:

  • 1 <= s.length <= 5 * 104

  • t.length == s.length t.length == s.length

  • s and t consist of any valid ascii character. st由任何有效的 ascii 字符组成。

I have most of the tests working correctly I am just failing some tests.我的大部分测试工作正常我只是没有通过一些测试。

This is what I have so far:这是我到目前为止所拥有的:

import java.nio.charset.*;

class Solution {

    public static boolean isIsomorphic(String s, String t) {
        s = s.toLowerCase();
        t = t.toLowerCase();
        int matchCount1 = 0;
        int matchCount2 = 0;
        matchCount1 = checkMatching(s);
        matchCount2 = checkMatching(t);
        System.out.print(matchCount1);
        System.out.print(matchCount2);
        return matchCount1 == matchCount2;
    }

    public static int checkMatching(String s) {
        int count = 0;
        int j = 0;
        for (int i = 0; i < s.length(); i++) { // s.length == 4
            char current = s.charAt(i); // current = 'p'
            j += 1;
            while (j < s.length() - 1) {
                if (current == s.charAt(j)) { // if p != a
                    count += 1;
                    break;
                } else {
                    j++; // j == 2
                }
            }
        }
        return count;
    }

    public static void main(String[] args) {
        String s = "paper";
        String t = "title";

        isIsomorphic(s, t);
    }
}

Failing test:失败测试:

If the strings s = "foo" and t = "bar" , the counts for both return 0 , where the answer should be 1 and 0 as "foo" contains two "o" characters.如果字符串s = "foo"t = "bar" ,则两者的计数都返回0 ,其中答案应该是10 ,因为"foo"包含两个"o"字符。

Any help would be appreciated as I feel like I'm one small change away.任何帮助将不胜感激,因为我觉得我只是一个小小的改变。

Basically what this task required is to determine whether the two Strings have identical structure, ie if string s contains character 'a' at indices 1, 3, 8 , we expect string t to have identical character (of whatever kind) at indices 1, 3, 8 and this character shouldn't be encountered anywhere else in the t .基本上,此任务所需的是确定两个字符串是否具有相同的结构,即如果字符串s在索引 1、3、8 处包含字符'a' ,我们期望字符串t在索引1, 3, 8处具有相同的字符(无论哪种) 1, 3, 8和这个字符不应该在t的其他任何地方遇到。 It this holds true for every character - the String are isomorphic .这对每个字符都适用——字符串是同构的。

We can find out it in a linear time O(n) by indexing positions of every character in a Map for both strings.我们可以通过为两个字符串索引 Map 中每个字符的位置,在线性时间O(n)内找到它。 It would be a map of type Map<Character,List<Integer>> , which associates a character with its indices.它将是 map 类型的Map<Character,List<Integer>> ,它将字符与其索引相关联。

And then we need to find out if all combinations indices of these strings match.然后我们需要找出这些字符串的所有组合索引是否匹配。 For that, we can dump the Values of each Map into a HashSet , it would be a set of type Set<List<Integer>> .为此,我们可以将每个 Map 的转储到HashSet中,它将是一组类型Set<List<Integer>> And compare these sets using Set.equals() ( reminder: two sets are equal if they contain the same elements, regardless of their order ).并使用Set.equals()比较这些集合(提醒:如果两个集合包含相同的元素,则它们相等,无论它们的顺序如何)。

That's how implementation might look like:这就是实现的样子:

public static boolean isIsomorphic(String s, String t) {
    if (s.length() != t.length()) return false; // early kill, if length of these string is not equal they are not isomorphic
    
    String first = s.toLowerCase();
    String second = t.toLowerCase();
    
    Set<List<Integer>> positions1 = getPositions(first);
    Set<List<Integer>> positions2 = getPositions(second);
    
    return positions1.equals(positions2);
}

public static Set<List<Integer>> getPositions(String str) {
    
    Map<Character, List<Integer>> positionsByCharacter = new HashMap<>();
    
    for (int i = 0; i < str.length(); i++) {
        char next = str.charAt(i);
        
        positionsByCharacter
            .computeIfAbsent(next, k -> new ArrayList<>())
            .add(i);
    }
    return new HashSet<>(positionsByCharacter.values());
}

main()

public static void main(String[] args) {
    System.out.println(isIsomorphic("egg", "add"));
    System.out.println(isIsomorphic("foo", "bar"));
    System.out.println(isIsomorphic("paper", "title"));
}

Output: Output:

true
false
true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM