简体   繁体   English

jvm比较String与StringBuffer.reverse()总是失败

[英]jvm comparing String with StringBuffer.reverse() always fails

I had a problem where I was to find all he substrings of a string that are palindromes. 我有一个问题,我要找到他所有回文字符串的子字符串。 Input would always be 1 word. 输入将始终为1个字。 The test input was aabaa. 测试输入为aabaa。 I decided to try be clever and make a string buffer of my substring then use the reverse method to compare with the original using String.equals. 我决定尝试聪明一些,并为我的子字符串创建一个字符串缓冲区,然后使用反向方法与使用String.equals的原始字符串进行比较。 It didn't work. 没用

import java.util.*

fun main(args: Array<String>) {
    val scan = Scanner(System.`in`)
    val input = scan.next()

    val found = ArrayList<String>()

    for (i in 0..input.length - 1) {
        for (j in 0..input.length - i) {
            val sub = input.substring(i, i + j)

            if (!found.contains(sub)) {
                // println(sub)
                found.add(sub)
                val rev = StringBuffer(sub).reverse()

                if (sub.equals(rev)) {
                    println(rev)
                }
            }
        }
    }
}

When I uncomment the first print statement the output look like this using test input aabaa 当我取消注释第一条打印语句时,使用测试输入aabaa的输出如下所示

a
aa
aab
aaba
aabaa
ab
aba
abaa
b
ba
baa

So I am getting the correct substrings, but the last if statement never resolves true and I don't know why this is. 所以我得到正确的子字符串,但是最后一个if语句永远不会解析为true,我也不知道为什么会这样。

sub is a String. sub是一个字符串。 rev is a StringBuffer. rev是一个StringBuffer。 They can't be equal, since they don't even have the same type. 它们不能相等,因为它们甚至没有相同的类型。

Additional notes: 补充笔记:

  • don't use StringBuffer. 不要使用StringBuffer。 Use StringBuilder. 使用StringBuilder。 StringBuffer is needlessly synchronized, and should not be used anymore (just like Vector shouldn't be used and ArrayList should be instead). StringBuffer是不必要地同步的,因此不应该再使用(就像不应该使用Vector一样,而应该使用ArrayList一样)。
  • for (i in 0..input.length - 1) can be written for (i in 0 until input.length) which is more elegant for (i in 0..input.length - 1)可以写for (i in 0 until input.length) ,这更优雅
  • input.substring(i, i + j) can't be right: at the end of the two loops, i would be length - 1, and j would be length - 1, and you would thus take a substring between length - 1 and 2 * length - 2. input.substring(i, i + j)可能不正确:在两个循环的末尾,i为length-1,j为length-1,因此您将在length-1之间采用一个子字符串和2 *长度-2。
  • to store unique results, use a HashSet, not an ArrayList. 若要存储唯一结果,请使用HashSet而不是ArrayList。 Calling contains() on a HashSet is O(1), whereas it's O(n) on an ArrayList. 在HashSet上调用contains()是O(1),而在ArrayList上是O(n)。
  • in Kotlin, unlike in Java, you can use a == b to test if a is equal to b, even if a and b are references. 在Kotlin中,与Java不同,即使a和b是引用,也可以使用a == b来测试a是否等于b。

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

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