zoukankan      html  css  js  c++  java
  • 查找主串中是否还有子串,如果有则返回匹配的第一个位置

    题目:

    查找主串中是否还有子串,如果有则返回匹配的第一个位置,否则返回-1

    #include <stdio.h>
    #include <string.h>
    
    int Index(char *origine, char *target)
    {
    	if (origine ==NULL||target == NULL)	//先检查是否为空
    	{
    		printf("there is a false
    ");
    		return -1;
    	}
    	int origStrLen = strlen(origine);
    	int targetLen = strlen(target);
    	int pos = -1;
    	int prePos = pos;
    	int i = 0;
    	int j = 0;
    
    	while(i < origStrLen && j < targetLen) // i,j都从0开始,故是<而不是<=
    	{
    		if (origine[i] == target[j])
    		{
    			++i;
    			++j;
    		}
    		else
    		{
    			i = i - j + 1;	//i退回到上次匹配首位的下一位
    			j = 0;			//每次从头开始从新查找子串
    		}	
    	}
    
    	if (j == targetLen)		//判断j是否等于targetLen,如果是则可以获取位置
    	{
    		prePos = pos;
    		pos = i - j;		//获取第一个匹配的位置
    	}
    	return pos+1;			//因为数组从0开始,所以要加1
    }
    
    int main()
    {
    	if(Index("hello aaaaa", "aa"))	//注意这里的调用要和下面的参数要一致
    		printf("子串在主串中,并且第一个匹配的字母在主串第%d位置
    ",Index("hello aaaaa", "aa"));
    	else
    		printf("子串不在主串中
    ");
        return 0;
    }

    执行结果:

    如果调用的是Index("hello aaaaa", "aA"),或其他不匹配的子串,则打印子串不在主串中,这里不演示了。

  • 相关阅读:
    南大算法设计与分析课程课后习题(1)
    南大算法设计与分析课程复习笔记(1) L1
    LeetCode-59. Spiral Matrix II
    LeetCode-58. Length of Last Word
    LeetCode-56. Merge Intervals
    LeetCode-55. Jump Game
    linux内核源码目录结构分析
    LeetCode-54. Spiral Matrix
    如何保证数据一致性
    CountDownLatch的简单使用
  • 原文地址:https://www.cnblogs.com/riasky/p/3363356.html
Copyright © 2011-2022 走看看