如何解释这段代码的某些部分?

时间:2015-02-22 22:49:08

标签: java

这个代码是测试,如果两个输入是anagram,它来自stackoverflow的答案,可以解决我的问题,但我不理解它的一部分。如果我不完全理解,我相信我什么都学不会。

    public static boolean isAnagram(String s1, String s2){
    //case insensitive anagram

    StringBuffer sb = new StringBuffer(s2.toLowerCase());
    for (char c: s1.toLowerCase().toCharArray()){
        if (Character.isLetter(c)){

            int index = sb.indexOf(String.valueOf(c));
            if (index == -1){
                //char does not exist in other s2
                return false;
            }
            sb.deleteCharAt(index);
        }
    }
    for (char c: sb.toString().toCharArray()){
        //only allow whitespace as left overs
        if (!Character.isWhitespace(c)){
            return false;
        }
    }
    return true;
}
  1. int index = sb.indexOf(String.valueOf(c));这意味着什么?通常indexOf()中有一个数字。 String.valueOf(c)会返回一个号码吗?

  2. if (!Character.isWhitespace(c))为什么有!在性格之前?那个有什么用途?

2 个答案:

答案 0 :(得分:1)

  1. sb.indexOf()将字符串作为参数,并返回该字符串所在的sb中的位置,如果不存在则返回-1。

  2. !表示不是。所以if语句说:如果c不是空白字符,那就做点什么。

答案 1 :(得分:0)

我记录了你的方法,你现在应该了解一切:

public static boolean isAnagram(String s1, String s2) {
    //Create a string buffer of the second string as lower case.
    StringBuffer sb = new StringBuffer(s2.toLowerCase());
    /*
     * Convert all characters of the first string to lowercase.
     * Split the string into an array of char
     * Loop over all chars, the current char is accessible by the variable c.
    */
    for (char c : s1.toLowerCase().toCharArray()) {
        //Character functionallity to check if the current character is a letter
        if (Character.isLetter(c))
        {
            //Retrieve the index of the current char in the second string, -1 will be returned if not found
            int index = sb.indexOf(String.valueOf(c));

            //if not found, we return false.
            if (index == -1) {                    
                return false;
            }

            //Remove the current char from the second string.
            sb.deleteCharAt(index);
        }
    }

    //Loop over all characters of the second string (you should understand this as it is the same logic as the first loop).
    for (char c : sb.toString().toCharArray()) {
        //only allow whitespace as left overs
        if (!Character.isWhitespace(c)) {
            //return false if something else then a whitespace is found
            return false;
        }
    }

    //If we arrive here it means that the algorithm was not able to prove false so we return true.
    return true;
}