1

I am trying to find out lexicographically smallest and largest substring of length z which is taken from input. I don't know why but the if condition is not working where I am trying to find the minimum substring.

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {

        Scanner ip=new Scanner(System.in);

        String s=ip.next();
        int z=ip.nextInt();
        String max="";
        String mini="";
        String x="";

        for(int i=0;i<s.length()-z;i++) {
                x=s.substring(i,i+z);
                if(x.compareTo((mini))<0) //this is not working
                    mini=x;

                if(x.compareTo((max))>0)
                    max=x;
            }
        System.out.print(mini);
        System.out.print(max);
    }
}
mzjn
  • 48,958
  • 13
  • 128
  • 248
Eduardo
  • 35
  • 4

1 Answers1

1

The problem in declaring of both variables mini and max

you already initialize them as empty string so the condition will not return the expected result when comparing them to x and their values won't change

you can initialize them:

 mini = s.substring(0, z);
 max  = s.substring(0, z);

Edit:

if you try to test this condition :

x.compareTo(("")) it will always return value bigger than 0 so mini won't change at any case.

Oghli
  • 2,200
  • 1
  • 15
  • 37