13.StrStr

class Solution {
/**
 * Returns a index to the first occurrence of target in source,
 * or -1  if target is not part of source.
 * @param source string to be scanned.
 * @param target string containing the sequence of characters to match.
 */
public int strStr(String source, String target) {
    //write your code here
   if (source == null || target == null) return -1;
   int sourceLength = source.length();
   int targetLength = target.length();
   if (sourceLength - targetLength < 0) return -1;
   for (int i = 0;  i < sourceLength - targetLength + 1; i++) {
       int sourceCurrentPosition = i;
       int targetCurrentPosition = 0;
       for (int j = 0; j < targetLength; j++) {
           if (source.charAt(sourceCurrentPosition) == target.charAt(targetCurrentPosition)) {
               sourceCurrentPosition++;
               targetCurrentPosition++;
           }
       }
       if (targetCurrentPosition == targetLength) return i;
   }
   return -1;
}
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容