繁体   English   中英

回文算法的时空复杂度

[英]Time and Space Complexity of Palindrome Algorithm

以下代码在 Java 中寻找回文的时间和空间复杂度是多少:

    public static boolean isPalindrome(String str) {
        return str.equals(new StringBuilder(str).reverse().toString());
    }

我知道 reverse() 是 O(n)。 toString() 也是 O(n)。 等于也是 O(n)。 这是否意味着这段代码是 O(n)?

至于空间复杂度,需要创建一个StringBuilder。 我不确定它被转换成字符串后会发生什么。 Java 是否为转换为字符串的 StringBuilder 分配空间,然后忘记 StringBuilder(允许它被垃圾收集器拾取)?

谢谢!

- - - - - 编辑 - - - - - - -

我想知道更多关于调用 isPalindrome 后在堆栈上创建的内容。 与说相比,它在空间方面的效率如何

谢谢。 我仍然不太了解这段代码在空间方面的效率如何? 究竟将在堆栈上创建什么,以及它的效率(在空间方面)与,比方说,

public boolean palindrome2(String str) {    
        int n = str.length();
        for( int i = 0; i < n/2; i++ )
            if (str.charAt(i) != str.charAt(n-i-1)) return false;
        return true;    
}

假设所有这些运算实际上都是O(n),我想您是对的:O(n)+ O(n)+ O(n)= 3 * O(n)(或O(3n),如果您愿意),则属于O(n)类别。

StringBuilder -创建一个匿名实例,在方法isPalindrome结束后,由于该对象的作用域仅是此方法的本地对象,因此没有对该对象的引用。 所以是的,它最终将由垃圾收集器处理。 最有可能不是立即,但我认为这与您无关。

public static boolean isPalindrome(String argument){    
    //remove special character    
    String done = argument.trim().replaceAll("[^a-zA-Z]+", " ");   
    //remove white spaces   
    String result = done.replaceAll("\\s", "");   
    //assign result string to argument   
    argument = result;   
    //convert string to a char then into a List of Charaters
    ArrayList<Character> characterList = (ArrayList<Character>) result.chars().mapToObj(c -> (char)c).collect(Collectors.toList());     
    //Using Collections reverse character List   
    Collections.reverse(characterList);
    //convert reversed List int a String    
    String reversedStr  = characterList.stream().map(String::valueOf).collect(Collectors.joining());   
    //Compare argument with reversedStr then return true or false   
    if(argument.equalsIgnoreCase(reversedStr))   
        return true;       
 public static boolean isPalindrome(String argument){
        //remove special character
        String done = argument.trim().replaceAll("[^a-zA-Z]+", " ");
        //remove white spaces
        String result = done.replaceAll("\\s", "");
        //assign result string to argument
        argument = result;
        //convert string to a char then into a List of Charaters
        ArrayList<Character> characterList = (ArrayList<Character>) result.chars().mapToObj(c -> (char)c).collect(Collectors.toList());
        //Using Collections reverse character List
        Collections.reverse(characterList);
        //convert reversed List int a String 
        String reversedStr  = characterList.stream().map(String::valueOf).collect(Collectors.joining());
        //Compare argument with reversedStr then return true or false
        if(argument.equalsIgnoreCase(reversedStr))
            return true;
        
        return false;
    }
    return false;   
}

暂无
暂无

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

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