13.StrStr

作者: 博瑜 | 来源:发表于2017-06-20 22:19 被阅读0次
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;
}
}

相关文章

网友评论

      本文标题:13.StrStr

      本文链接:https://www.haomeiwen.com/subject/cawaqxtx.html