【问题标题】:Can we take two string from one String in if statement?我们可以在 if 语句中从一个字符串中取出两个字符串吗?
【发布时间】:2020-05-04 04:24:29
【问题描述】:

我想打印两个最大和最小的字符串字典。打印最大的,但最小的输出与最大的相同。我的代码有什么问题?

公共类解决方案{

public static String getSmallestAndLargest(String s, int k) {
   String sequence = s.substring(0,k);
    String smallest = sequence;
    String largest = sequence;

    for(int i=0;i<=(s.length()-k); i++){

        sequence= s.substring(i,(i+k));

        if    (sequence.compareTo(smallest)<0){
            sequence=smallest;
        }
        if (sequence.compareTo(largest)>0){
            sequence=largest;
        }

            }
    // Complete the function
    // 'smallest' must be the lexicographically smallest substring of length 'k'
    // 'largest' must be the lexicographically largest substring of length 'k'

    return smallest + "\n" + largest;
}




public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String s = scan.next();
    int k = scan.nextInt();
    scan.close();

    System.out.println(getSmallestAndLargest(s, k));
}

}

【问题讨论】:

  • 在为其赋值时,最小和最大需要朝向 LHS。所以,它必须是最大的 = 序列和最小的 = 序列。
  • @sara 但是为什么我们需要在 LHS 上写作?
  • 变量=值;不是相反;这是 Java 语言语法。

标签: java string substring lexicographic


【解决方案1】:
if(sequence.compareTo(smallest)<0){
    smallest = sequence;
}
if (sequence.compareTo(largest)>0){
    largest = sequence;
}

您将sequencesmallestlargest 进行比较。而您的sequencefor loop 的每次迭代中都会发生变化。在if condition 中,您正在检查您当前的sequence 是否小于/大于您的smallestlargest,如果是,您必须更新您的smallestlargest 值。

【讨论】:

    【解决方案2】:
        if (sequence.compareTo(smallest)<0){
            smallest=sequence;
        }
        if (sequence.compareTo(largest)>0){
            largest=sequence;
        }
    

    在Java 语言中,变量赋值是这样完成的。

    variable = value;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-11
      • 1970-01-01
      • 2023-03-31
      • 2019-04-25
      • 2020-04-28
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      相关资源
      最近更新 更多