zoukankan      html  css  js  c++  java
  • 华为招聘机试整理1:删除子串

    华为招聘机试整理1:删除子串

    题目:删除子串
    题目描写叙述:
    仅仅要是原串中有同样的子串就删掉,无论有多少个,返回子串的个数。
    题目分析:
    我们对照该题与《HWOJ 在一个字符中删除第二个字符出现过的全部字符》《HWOJ 实现一个听高级的字符匹配算法》都是不一样的。一定要注意区分
    所以我们这道题不适合用哈希表来完毕。


    我们能够利用指针来完毕
    算法思路:
    ①利用字符串str循环。之后将和sub_str长度复制给一个新的字符串temp
    所以我们这里须要用malloc来动态申请内存空间。而用free来释放malloc申请的空间
    这里我们採用什么函数复制呢?memcpy还是strcpy呢?
    补充:
    strcpy和memcpy主要有下面2方面的差别。
    1、复制的内容不同。

    strcpy仅仅能复制字符串,而memcpy能够复制随意内容,比如字符数组、整型、结构体、类等。
    2、复制的方法不同。

    strcpy不须要指定长度,它遇到被复制字符的串结束符""才结束,所以easy溢出。memcpy则是依据其第3个參数决定复制的长度。


    尽管做的是字符串,所以我们这里由于须要指定长度,所以我们选择用memcpy
    ③之后去比較temp和sub_str。用str_cmp去比較。假设同样说明有同样子串,直接str = str + len1;
    假设不同说明没有,直接保存在*result中。且分别加1

    ===============================================================================
    參考代码:

    //删除子串.cpp
    //2014.7.9 hepanhui
    #include <iostream>
    #include <string>
    const int maxn = 1000;
    using namespace std;
    
    int delete_sub_str(const char *str,const char *sub_str,char *result)
    {
        //非法输入
        if(str == NULL || sub_str == NULL)
            return 0;
    
        //初始化
        int len1 = strlen(sub_str);
        int cnt = 0;
        char *temp = NULL;
    
        temp = (char *)malloc(len1 + 1);
        while(*str)
        {
            memset(temp, 0, len1 + 1);
            memcpy(temp,str,len1);
            if(strcmp(temp,sub_str) == 0)
            {
                cnt ++;
                str = str + len1;
            }
            else
            {
                *result = *str;
                str++;
                result++;
            }
        }
        *result++ = '';
        free(temp);
        return cnt;
    }
    
    int main()
    {
        char str[maxn];
        char sub_str[maxn];
        char result[maxn];
        gets(str);
        gets(sub_str);
        int num = delete_sub_str(str,sub_str,result);
        cout << num << endl;
        cout << result << endl;
    }
    

    调试过程易犯的错误:
    ①记住不能对指针或者常量字符串用sizeof求长度;常量转化为很量字符串,须要强制类型转换;所以我们初始化的时候不能用sizeof(temp)
    ②记住须要加上result++ = '';
    ③malloc返回值是void
    ,申请时须要强制转换成须要的类型,所以(char )不能忘记
    ④必须每次循环都要把temp清空,申请的区域值是随机的
    综上所述。我们以后须要动态申请内存空间的时候。
    1)初始化 char *
    temp = NULL
    2)申请内存空间temp = (char *)malloc(len1 + 1); 这里还须要注意假设是整型长度记得要加上sizeof(int)
    score=(int*
    )malloc(sizeof(int)*(n+1));
    3)清空memset(temp, 0, len1 + 1);
    4)释放内存free(temp);


查看全文
  • 相关阅读:
    UVA 10617 Again Palindrome
    UVA 10154 Weights and Measures
    UVA 10201 Adventures in Moving Part IV
    UVA 10313 Pay the Price
    UVA 10271 Chopsticks
    Restore DB後設置指引 for maximo
    每行SQL語句加go換行
    种服务器角色所拥有的权限
    Framework X support IPV6?
    模擬DeadLock
  • 原文地址:https://www.cnblogs.com/ldxsuanfa/p/10832502.html
  • Copyright © 2011-2022 走看看