牛客网-编程题练习

day 01

第一题:

题目:在字符串中查找第一次出现且只出现一次的字符。
如输入“asdfgfdsa”,则输出‘g’。

算法解析:

算法1:
从头到尾开始扫描这个字符串。当访问到某个字符时,一次和后面的字符比较。如果后面字符没有与该字符相同的字符,就说明这个字符是第一次出现的字符。如果字符串有n个字符,每个字符可能与后面的O(n)个字符相比较,因此这种思路时间复杂度是O(n^2)。

解法二,

既然题目与字符串中字符的次数有关,我们可以来统计一下字符出现的次数。那么怎么统计这个次数呢

我们需要一种容器,这种容器可以存放字符出现的次数。并且次数和还存在着一种映射关系。

能够满足这种需求的容器就是哈希表了。我们可以将字符的ASCII码值作为哈希表的下标,即key值。字符出现的次数,作为哈希表对应下标内容。即value值。

这里写图片描述

#include<stdio.h>
char firstNotRepeating(char* pString)
{
    if(pString==NULL)
    {
        return '\0';
    }
    int TableSize=258;
    int  HashTable[TableSize];
    //初始化哈希表
    int i=0;
    for(;i<TableSize;i++)
    {
        HashTable[i]=0;

    }
    //根据字符acsii码值
    //确定哈希表的key值和哈希表的value值

    char *HashKey=pString;
    while(*HashKey!='\0')
    {
        //(*HashKey)++是key值变化
        //HashTable[HashKey]++是value值加1
        //如果遇到相同的字符,value加1
        HashTable[*(HashKey++)]++;

    }


    HashKey=pString;

    while(*HashKey!='\0')
    {
        //HashTable[*HashKey]==1
        //则说明找到了只出现一次的字符

        if(HashTable[*HashKey]==1)
        {
            return *HashKey;
        }
        HashKey++;

    }
    return '\0';

}
int main()
{
        //测试字符串中只出现一次的字符
    char str1[]="hheello";
    char ret_1=firstNotRepeating(str1);
    //测试字符串中不存在只出现一次的字符
    char str2[]="world world";
    char ret_2=firstNotRepeating(str2);
    //测试所有字符串只出现一次
    char str3[]="owmuch";
    char ret_3=firstNotRepeating(str3);
    //测试空串
    char str4[]="        ";
    char ret_4=firstNotRepeating(str3);
    printf("expected o,actual :%c\n",ret_1);
    printf("expected  ,actual :%c\n",ret_2);
    printf("expected o,actual :%c\n",ret_3);
    printf("expected  ,actual :%c\n",ret_4);

    return 0;

}

运行结果:

expected o,actual :o
expected  ,actual : 
expected o,actual :o
expected  ,actual :o

第二题:

题目:Implement int sqrt(int x).
Compute and return the square root of x.(实现整数倍根号(int x)。
计算并返回x的平方根。)

解析:

第三题:

题目
这里写图片描述

解析:

day 02

第一题:
Given a collection of numbers, return all possible permutations.

For example,
[1,2,3]have the following permutations:
[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2], and[3,2,1].

汉语翻译:给定一个数字集合,返回所有可能的排列。例如,[1,2,3]有下列排列:[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2]和[3,2,1]。

第二题:

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

For example:
Given”25525511135”,

return[“255.255.11.135”, “255.255.111.35”]. (Order does not matter)
给定只包含数字的字符串,通过返回所有可能的有效IP地址组合来还原它。例如:给定“25525511135”,返回[“255.255.11.135”、“255.255.111.35”]。(命令不重要)

猜你喜欢

转载自blog.csdn.net/zgege/article/details/80945855