Implement strStr()

来源:互联网 发布:织梦cms使用手册 编辑:程序博客网 时间:2024/06/05 10:10

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

For example: source = “abcdefj”; target = “cde”, return 2

O(mn), 主要掌握双重for循环的写法。注意每次要先判断输入的合法性。KMP需要大致了解。复杂度是O(n)。

public int strstr(string source, string target){if( source == null || target == null ){<span style="white-space:pre"></span>return -1;<span style="white-space:pre"></span>}int i = 0, j = 0;for( i = 0; i < source.Length - target.Length + 1; i++ ){for ( j = 0; j < target.Length; j++ ){if( target(j) != source(i+j) ){<span style="white-space:pre"></span>break;<span style="white-space:pre"></span>}}if( j == target.Length ){return i;}}return -1;}




0 0
原创粉丝点击