如何编写compareTo()方法以字典顺序来字符串而不使用.compareTo()方法

时间:2018-03-21 18:44:36

标签: java compareto

这是我创建的名为Movie的类中的方法。

我现在将代码更改为此,因此它只应在离开for循环时返回一个值,但它仍然给出了错误的答案。

    public int compareTo(Movie other){
    String a = this.name.toLowerCase();
    String b = other.name.toLowerCase();
    int shorter = 0;
        if (a.length()>b.length())
            shorter = b.length();
        else
            shorter = a.length();
        int diff = 2;

        while (diff !=0){
            for (int i = 0; i < shorter; i++) {
            //a<b<c<d
            diff = a.charAt(i) - b.charAt(i);
                if (diff < 0)
                    diff =  1;
                else if (diff >0)
                    diff =  -1;
                else  if (diff == 0 && a.length()<b.length())
                    diff =  1;
                else if (diff == 0 && a.length()>b.length())
                    diff =  -1;
                else 
                    diff =  0;
        }
        }
        return diff;}

指示说:写一个compareTo:使用以下签名public int compareTo(Movie other)。如果此电影的名称在字典上与其他电影的名称相同,则返回0; -1如果此电影的名称按字典顺序小于另一个电影的名称; 1如果此电影的名称按字典顺序大于其他电影的名称。

2 个答案:

答案 0 :(得分:0)

您的实施存在缺陷。

考虑两个标题:Gone With the WindGo West!。它们共享相同的前两个字母,因此diff对于这两个字母将为0。一旦我们点击第三个字符'n'和'',我们就需要进行比较。

为此,我们进行迭代,直到找到不同的字母,然后停止:

int diff;
for(int i = 0; i < shorterWord.length(); i++) {
   diff = shorterWord.charAt(i) - longerWord.charAt(i);
   if(diff != 0) {
     break;
   }
}
return diff;

但是等等!如果短词中的所有字母都在较长的单词中怎么办?比如,如果你的标题是SawSaw II - 那么呢?

如果退出循环后diff仍为0,我们知道这两个词是相同的,或者我们遇到了这种情况,所以我们可以添加一个快速检查:

if(!shorterWord.equals(longerWord)) {
  // The words are not the same, so handle this how you will
}

(我没有实现这个,因为我不确定你真的想要如何处理它。可能总是设置diff = 1diff = -1取决于哪个词更长,是有意义的。)

你的工作不起作用的原因有两个。你有这样的结构:

diff = 2;
while(diff != 0) {
    for (int i = 0; i < shorter; i++) {
      // set diff
    }
}

问题是while循环只会在退出for循环后评估diff条件。这没有任何意义 - 只有当您退出for循环时,diff才会设置较短单词的最后一个字母的比较。

答案 1 :(得分:-1)

这可以进一步优化速度(这将使它类似于Java的String.compareTo()),但...... (随意回答这个问题,因为这听起来像是一个&#39;作业问题&#39;问题)

public int compareTo(Movie other) {
    String tn = this.name;
    String on = other.name;

    // quick check - equality - safe to leave out if equals() is cheating
    // but guard against division by zero below.
    if (tn.equals(on)) {
        return 0;
    }

    for (int i = 0; i < Math.min(tn.length(), on.length()); i++) {
        int tc = (int)tn.charAt(i);
        int oc = (int)on.charAt(i);
        if (tc != oc) {
            // return larger char...
            return toOne(tc - oc);
        }
    }
    // ...or return larger string
    return toOne(tn.length() - on.length());
}
// just converts any +-N to respective +-1
private int toOne(int c) {
    return c / Math.abs(c);
}
相关问题