英文:
Can we take two string from one String in if statement?
问题
public class Solution {
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) {
smallest = sequence;
}
if (sequence.compareTo(largest) > 0) {
largest = sequence;
}
}
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));
}
}
英文:
I want to print Two String Lexicographical largest and smallest. Largest is printed but smallest give output same as largest. Whats problem in my code?
public class Solution {
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));
}
}
答案1
得分: 1
if sequence.compareTo(smallest) < 0:
smallest = sequence
if sequence.compareTo(largest) > 0:
largest = sequence
您正在将sequence与smallest和largest进行比较。并且您的sequence在每次for循环迭代中都会更改。在if条件内部,您正在检查当前的sequence是否小于/大于您的smallest和largest,如果是,则必须更新您的smallest和largest值。
英文:
if(sequence.compareTo(smallest)<0){
smallest = sequence;
}
if (sequence.compareTo(largest)>0){
largest = sequence;
}
You are comparing sequence with the smallest and largest. And your sequence changes in every iteration of the for loop. And inside the if condition, you are checking if your current sequence is smaller/larger than your smallest and largest and if so, you have to update your smallest and largest values.
答案2
得分: 1
if (sequence.compareTo(smallest) < 0){
smallest = sequence;
}
if (sequence.compareTo(largest) > 0){
largest = sequence;
}
在Java语言中,变量赋值的方式如下。
变量 = 值;
英文:
if (sequence.compareTo(smallest)<0){
smallest=sequence;
}
if (sequence.compareTo(largest)>0){
largest=sequence;
}
In Java language, variable assignment is done as follows.
variable = value;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论