如何验证两个相同长度的字符串,并且每个字符有一个值,没有重复的Java

时间:2019-01-30 18:43:22

标签: java string match

如何验证两个字符串是否彼此匹配。一个字符匹配一个字符,没有重复。

<item.*?attr="[^>]*>

2 个答案:

答案 0 :(得分:0)

给这个镜头一个逻辑,在那里就可以进行微调

public static void main(String[] args) {
    System.out.println(" Result:"+sillyStringCompare("ABC", "DEF"));
    System.out.println(" Result:"+sillyStringCompare("BIKE", "FGEH"));
    System.out.println(" Result:"+sillyStringCompare("Alex", "BoB"));
    System.out.println(" Result:"+sillyStringCompare("Mom", "DaD"));
}

private static boolean sillyStringCompare(String stringOne, String stringTwo){
    System.out.print('"'+stringOne+'"'+" ---> "+'"'+stringTwo+'"');
    if(stringOne.length()!=stringTwo.length())
        return false;

    if(duplicateLetterInString(stringOne, 0))
        return false;

    if(duplicateLetterInString(stringTwo, 0))
        return false;

    return true;
}

private static boolean duplicateLetterInString(String string, int index) {
    char compareChar = string.charAt(index);

    char[] charArray = string.toCharArray();
    for (int i = 0; i < charArray.length; i++) {
        if (charArray[i] == compareChar && i != index)
            return true;
    }

    return string.length() > index + 1 && duplicateLetterInString(string, ++index);
}

输出:

"ABC" ---> "DEF" Result:true
"BIKE" ---> "FGEH" Result:true
"Alex" ---> "BoB" Result:false
"Mom" ---> "DaD" Result:false

答案 1 :(得分:0)

您可以使用Map将字符串1中的字母映射到字符串2中:

static boolean match(String str1, String str2){
    // First check len
    if (str1.length() != str2.length()) return false;

    // Create the map
    Map<Character, Character> letterMap = new HashMap<Character, Character>();

    // Compare
    for (int i = 0; i < str1.length(); i++) {
        char c1 = str1.charAt(i);
        char c2 = str2.charAt(i);
        // New letter in string 1?
        if (!letterMap.containsKey(c1)) {
            // Make sure the letter c2 is not already mapped to something else
            if (letterMap.containsValue(c2)) return false;
            // Add to map
            letterMap.put(c1, c2);
        }
        // Already in map? (Not a new letter in str1)
        else {
            // Make sure it's the correct c2
            if (letterMap.get(c1) != c2) return false;
        }
    }
    return true;
}