Implement strStr() LeetCode solution in Java
1class Solution {2public int strStr(String haystack, String needle) {34if (needle.length() > haystack.length()) {5return -1;6}7if (needle.length() == haystack.length()) {8if (haystack.equals(needle)) {9return 0;10}11return -1;12}1314int i = 0;15int j = 0;16while (i < needle.length() && j < haystack.length()) {17if (needle.charAt(i) == haystack.charAt(j)) {18i++;19j++;20if (i == needle.length()) {21return j - needle.length();22}23} else {24j = j - i + 1; // backtrack to last pos+1 where there was a probable match25i = 0;26}27}2829return -1;30}31}