zoukankan      html  css  js  c++  java
  • 蛮力算法02

    ——找东西,是个很重要的命题。

    顺序查找和字符串匹配也是蛮力求解的典范。

    顺序查找

    template<typename ObjectType>
    int Find( ObjectType *arr,int arrLen,ObjectType findItem )
    {
        for (int i=0;i<arrLen;++i)
        {
            if (arr[i] == findItem)
            {
                return i;
            }
        }
     
        return -1;
    }

    字符串蛮力匹配

    RandomCreate rd;
    ConsoleOutput<char> output;
     
    //65,123
    const int ARR_SOURCE_LEN = 20;
    const int ARR_FIND_LEN = 1;
    char sourceArr[ARR_SOURCE_LEN];
    char findArr[]={'c'};
     
    rd.RandomChars(sourceArr,ARR_SOURCE_LEN,97,123);
     
    cout<<"要查找的源字符串: "<<endl;
    output.OutputArray(sourceArr,ARR_SOURCE_LEN);
     
    cout<<"要查找的串:"<<endl;
    output.OutputArray(findArr,ARR_FIND_LEN);
     
    int findIndex = -1;
    for (int i=0;i<ARR_SOURCE_LEN-ARR_FIND_LEN;++i)
    {
        int j=0;
        for (;j<ARR_FIND_LEN;++j)
        {
            if (sourceArr[i+j] != findArr[j])
            {
                break;
            }
        }
        if (j == ARR_FIND_LEN)
        {
            findIndex = i;
            break;
        }
    }
     
    cout<<"查找结果是: "<<findIndex<<endl;
  • 相关阅读:
    5.3二叉树的运算
    hadoop namenode切换
    org.apache.hadoop.security.AccessControlException
    Hive中的日志
    命令大全详解
    python深浅copy
    awk命令
    head&tail命令
    cut命令
    理解inode
  • 原文地址:https://www.cnblogs.com/sharpfeng/p/2660922.html
Copyright © 2011-2022 走看看