uopspop

Untitled

Sep 5th, 2020
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.78 KB | None | 0 0
  1. // attention: pay attention the the end index limit on all arrays (including strings)
  2.  
  3. class Solution {
  4.     public int strStr(String haystack, String needle) {
  5.         if (null == haystack) return -1;
  6.         if (null == needle) return -1;
  7.         if (needle.isEmpty()) return 0; // if empty string, return 0
  8.        
  9.         for (int i = 0; i <= haystack.length() - needle.length(); i++) {
  10.             boolean isFound = true;
  11.             for (int j = 0; j < needle.length(); j++) {
  12.                 if (haystack.charAt(i+j) != needle.charAt(j)) {
  13.                     isFound = false;
  14.                     break;
  15.                 }
  16.             }
  17.            
  18.             if (isFound) {
  19.                 return i;                
  20.             }
  21.         }
  22.         return -1;
  23.     }
  24. };
Add Comment
Please, Sign In to add comment