http://www.technicalpage.net/search/label/SQL

SubStringOfArray

// Find the smallest substring of the string containing all the characters of the array. For example: array = [a,b,c] and string="abbccaccbbccba"

//output = cba

 

package testSubstring;

public class SmallestSubString {

       public static void main(String[] Args) {

             String[] array = {"a","b","c"};

             String givenText = "abbccaccbbccba";

//           System.out.println("The expected string = "+Interview25.subString({"a","b","c"}, "abbccaccbbccba"));//Error

             System.out.println("The expected string = "+Interview25.subString(array, "abbccaccbbccba"));

       }

 

       public static String subString(String[] array, String givenText ) {

//           String[] array = {"a","b","c"};

//           String givenText = "abbccaccbbccba";

             String expectedText = null;

             int textLength = givenText.length();

             for(int i=1;i<3;i++) {

                    for(int j=1;j<givenText.length();j++) {

                           if(((i+1)<3)&&((j+1)<textLength)) {

                           if((array[i]).equals(Character.toString(givenText.charAt(j)))) {

                                 if(((array[i-1]).equals(Character.toString(givenText.charAt(j-1))))||((array[i-1]).equals(Character.toString(givenText.charAt(j+1))))){

                                        if(((array[i+1]).equals(Character.toString(givenText.charAt(j-1))))||((array[i+1]).equals(Character.toString(givenText.charAt(j+1))))){

                                        expectedText = (Character.toString(givenText.charAt(j-1))).concat(Character.toString(givenText.charAt(j))).concat(Character.toString(givenText.charAt(j+1)));

                                        }}}

                           }

                    }

             }

             System.out.println(expectedText);

             return expectedText;

       }

 

}

 

Output:

cba

The expected string = cba

No comments:

Post a Comment