class Solution { // 定义一个名为strStr的方法,接收两个字符串参数haystack和needle public int strStr(String haystack, String needle) { // 获取haystack的长度 int len1 = haystack.length(); // 获取needle的长度 int len2 = needle.length(); // 遍历haystack,从索引0开始,直到剩余长度小于needle的长度 for (int i = 0; i + len2 <= len1; i++) { // 初始化标志位为true,表示当前子串与needle匹配 boolean flag = true; // 遍历needle的每个字符 for (int j = 0; j < len2; j++) { // 如果当前位置的字符不匹配,则将标志位设为false并跳出循环 if (haystack.charAt(i + j) != needle.charAt(j)) { flag = false; break; } } // 如果标志位仍为true,说明找到了匹配的子串,返回当前起始索引 if (flag) { return i; } } // 如果没有找到匹配的子串,返回-1 return -1; } }
11-09
276
08-29
157
09-03