1 package org.feistymeow.algorithms;
4 * used to find strings in other strings.
6 * part of google interview prep.
9 public class SubstringFinder
13 * returns the position of 'x' in 'y', or returns a negative number.
15 public int findXinY(String x, String y)
17 if ((x == null) || (y == null))
18 return -1; // nulls are invalid to compare.
19 if (y.length() < x.length())
20 return -1; // x cannot be found in shorter string.
21 for (int yIter = x.length() - 1; yIter < y.length(); yIter++) {
24 * xIter has to start at valid value in x, and that needs to be at end of x. board actually had uncorrected error here, where
25 * xIter started at yIter, which is really wrong.
27 // simplified xIter which was inducing all sorts of OBOBs. even though i found the end in yIter,
28 // i go forwards on xIter.
29 for (int xIter = 0; xIter < x.length(); xIter++) {
30 int yComparePosition = (yIter - x.length() + 1) + xIter;
31 if (x.charAt(xIter) != y.charAt(yComparePosition)) {
32 // System.out.println("no match -- y[" + yIter + "]=" + y.charAt(yPosn) + " x[" + xIter + "]=" + x.charAt(xIter));
38 int toReturn = yIter - x.length() + 1;
39 // System.out.println("found at position " +toReturn );
47 public static void main(String[] argv)
49 SubstringFinder sf = new SubstringFinder();
51 String x1 = "petunia";
52 String y1 = "sometimes my flowers are roses and sometimes they are petunias and sometimes they are turnips.";
53 if (sf.findXinY(x1, y1) != 54) {
54 System.out.println("FAILURE: did not find at right index for test 1");
56 System.out.println("OKAY: found substring at right index for test 1");
61 if (sf.findXinY(x2, y2) != 2) {
62 System.out.println("FAILURE: did not find at right index for test 2");
64 System.out.println("OKAY: found substring at right index for test 2");
69 if (sf.findXinY(x3, y3) >= 0) {
70 System.out.println("FAILURE: found non-existent string for test 3");
72 System.out.println("OKAY: did not find substring for test 3");