• LeetCode_28. Implement strStr()


    28. Implement strStr()

    Easy

    Implement strStr().

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

    Example 1:

    Input: haystack = "hello", needle = "ll"
    Output: 2
    

    Example 2:

    Input: haystack = "aaaaa", needle = "bba"
    Output: -1
    

    Clarification:

    What should we return when needle is an empty string? This is a great question to ask during an interview.

    For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

    package leetcode.easy;
    
    public class ImplementStrStr {
    	@org.junit.Test
    	public void test() {
    		String haystack1 = "hello";
    		String needle1 = "ll";
    		String haystack2 = "aaaaa";
    		String needle2 = "bba";
    		System.out.println(strStr(haystack1, needle1));
    		System.out.println(strStr(haystack2, needle2));
    	}
    
    	public int strStr(String haystack, String needle) {
    		char[] source = haystack.toCharArray();
    		int sourceOffset = 0;
    		int sourceCount = haystack.length();
    		char[] target = needle.toCharArray();
    		int targetOffset = 0;
    		int targetCount = needle.length();
    		int fromIndex = 0;
    		if (fromIndex >= sourceCount) {
    			return (targetCount == 0 ? sourceCount : -1);
    		}
    		if (fromIndex < 0) {
    			fromIndex = 0;
    		}
    		if (targetCount == 0) {
    			return fromIndex;
    		}
    
    		char first = target[targetOffset];
    		int max = sourceOffset + (sourceCount - targetCount);
    
    		for (int i = sourceOffset + fromIndex; i <= max; i++) {
    			/* Look for first character. */
    			if (source[i] != first) {
    				while (++i <= max && source[i] != first)
    					;
    			}
    
    			/* Found first character, now look at the rest of v2 */
    			if (i <= max) {
    				int j = i + 1;
    				int end = j + targetCount - 1;
    				for (int k = targetOffset + 1; j < end && source[j] == target[k]; j++, k++)
    					;
    
    				if (j == end) {
    					/* Found whole string. */
    					return i - sourceOffset;
    				}
    			}
    		}
    		return -1;
    	}
    }
    
  • 相关阅读:
    Oracle中创建视图
    SQL Server 2012 Express安装图解
    oracle学习笔记
    Oracle中视图的创建和处理方法
    DDL、DML和DCL的理解
    ROS学习--如何结合launch文件使用参数服务器
    stm32多块开发板can总线互联卡死问题
    ROS CAN总线设备接入(二)can总线数据提取和以ros topic形式发布
    ROS CAN总线设备接入(一)Linux动态库的显式调用
    ROS .so载入undefined reference to `dlopen'问题
  • 原文地址:https://www.cnblogs.com/denggelin/p/11557870.html
Copyright © 2020-2023  润新知