SoFunction
Updated on 2025-03-07

Start with the simulation implementation of algorithm exercises

The simulation implementation of this method is not as profound as I imagined, but it is the most common traversal search

Idea: First find the first identical character, and then compare the following characters in turn. If they are all equal, it means that the search is successful.

/**
    * Find the first occurrence of the string pattern in str
    * @param str
    * @param pattern
    * @return
    */ 
  public int firstIndexOf(String str, String pattern) { 
    for (int i = 0; i < (() - ()); i++) { 
      int j = 0; 
      while (j < ()) { 
        if ((i + j) != (j)) break; 
        j++; 
      } 
      if(j==()) return i; 
    } 
    return -1; 
  } 
 
  /**
    * Find the last occurrence of the string pattern in str
    * @param str
    * @param pattern
    * @return
    */ 
  public int lastIndexOf(String str, String pattern) { 
    for (int i = () - (); i >= 0; i--) { 
      int j = 0; 
      while (j < ()) { 
        if ((i + j) != (j)) break; 
        j++; 
      } 
      if (j == ()) return i; 
    } 
    return -1; 
  } 
 
  /**
    * Find where the string pattern appears in str
    * @param str
    * @param pattern
    * @return
    */ 
  public List<Integer> indexOf(String str, String pattern) { 
    List<Integer> indexs = new ArrayList<Integer>(); 
    for (int i = 0; i < (() - ()); i++) { 
      int j = 0; 
      while (j < ()) { 
        if ((i + j) != (j)) break; 
        j++; 
      } 
      if (j == ()) (i); 
    } 
    return indexs; 
  } 

The same more commonly used method is actually the implementation of the call

/**
    * Determine whether the string pattern exists in str
    * @param str
    * @param pattern
    * @return
    */ 
  public boolean contains(String str, String pattern) { 
    return firstIndexOf(str, pattern) != -1; 
  }