一.题目

实现strStr()

二.思路

needle 作为外循环,haystack 作为内循环,注意这里 if ((index + needle.length() - 1) > (haystack.length() - 1))

	public int strStr(String haystack, String needle) {
		if (needle.equals("")) {
			return 0;
		}
		int index = 0;
		for (int i = 0; i < needle.length(); i++) {
			for (int j = 0; j < haystack.length(); j++) {
				if (haystack.charAt(j) == needle.charAt(i)) {
					index = j;
					if ((index + needle.length() - 1) > (haystack.length() - 1)) {
						return -1;
					} else if (haystack.substring(index,
							index + needle.length()).equals(needle)) {
						return index;
					}
				}
			}
		}
		return -1;
	}

相关文章:

  • 2021-04-27
  • 2021-06-20
  • 2021-10-11
  • 2022-01-02
  • 2022-12-23
  • 2021-08-10
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-01
  • 2021-06-24
  • 2021-07-25
  • 2022-12-23
  • 2021-10-18
相关资源
相似解决方案