пятница, 6 ноября 2015 г.

Code Challenge: Substring Search

Specification/Rules of problem:
  • Find the index of the first occurrence of an arbitrary length substring within a string.
  • Use what ever language you prefer.
  • Must be done at the character/int/byte level.
  • No Regex or String functions may be used apart from charAt/getBytes/getCharArray etc equivalent functions ie functions for retrieving the characters in whatever form.

My solution in Java:
public class SubstringFinder {
  public static final int NOT_FOUND = -1;


  public int findFirst( String src, String what ){
    char[] cSrc = src.toCharArray();
    char[] cWhat = what.toCharArray();
    return findFirst(cSrc, cWhat);
  }

  private int findFirst(char[] cSrc, char[] cWhat) {
    if( cWhat.length == 0)
      return NOT_FOUND;

    char firstChar = cWhat[0];
    int foundMatchAtIdx = NOT_FOUND;

    for( int idx = 0; idx < cSrc.length; idx ++){
      if( cSrc[idx] == firstChar ){
        char[] restOfSrc =  Arrays.copyOfRange(cSrc, idx + 1, cSrc.length);
        char[] restOfWhat = Arrays.copyOfRange(cWhat, 1, cWhat.length);
        if( arrayStartsWith( restOfSrc, restOfWhat) ){
          foundMatchAtIdx = idx;
          break;
        }
      }
    }

    return foundMatchAtIdx;
  }

  private boolean arrayStartsWith( char[] array, char[] other ){
    if(other.length > array.length) return false;

    for( int i = 0; i < other.length; i++)
      if(  array[i] != other[i] )
        return false;

    return true;
  }
}

Комментариев нет:

Отправить комментарий