【算法集训】基础数据结构:二、字符串

字符串在C语言中我感觉还是比较难的,主要是C中没有String,只能使用字符数组来创建字符串。这个就有点难受了

第一题 LCR 122. 路径加密

https://leetcode.cn/problems/ti-huan-kong-ge-lcof/description/
第一题本来是力扣05的一道题,但是变题了。
不过我感觉变的这个还比较简单了,不需要创建多余的空间,一对一替换就可以了。
思路很简单,遍历字符,遇到.就替换为空格,如果是其他的就原样输出,这个最烦的是每个结尾必须加‘\0’,确实有点难受

char* pathEncryption(char* path) {
    int len = strlen(path);
    char *res = (char *)malloc(sizeof(char) * len +1);
    int index = 0;
    for(int i = 0; i < len; ++i) {
        if(path[i] == '.') {
            res[index++] = ' ';
        }else {
            res[index++] = path[i];
        }
    }
    res[index] = '\0';
    
    return res;
}

第二题 1876. 长度为三且各字符不同的子字符串

https://leetcode.cn/problems/substrings-of-size-three-with-distinct-characters/description/
遍历数组每三个字符进行一次比较,看他们是否互相相等,否则结果数+1;

int countGoodSubstrings(char* s) {
    int len = strlen(s);
    int res = 0;
    for(int i = 0; i < len - 2; ++i) {
        char a = s[i];
        char b = s[i + 1];
        char c = s[i + 2];
        if(a != b && b != c && a != c) {
            res++;
        }
    }
    return res;
}

第三题 LCP 17. 速算机器人

https://leetcode.cn/problems/nGK0Fy/description/
给你一个x和y的初始值,然后给一个字符串,这个字符串中只有大写A和B,对应的A和B有x和y的计算方法,根据字母的顺序进行运算,最后将x+y即可;
这一题我出现了两个错误:
1、C语言中字符必须用‘’单引号;
2、如果非全局使用变量直接在局部定义即可;
所以基础还是非常重要的;

int calculate(char* s){
    int len = strlen(s);
    int x = 1;
    int y = 0;
    for(int i = 0; i < len; ++i) {
        if(s[i] == 'A') {
            x = 2 * x + y;
        }else if(s[i] == 'B') {
            y = 2 * y + x;
        }
    }
    return x + y;
}

第四题 2011. 执行操作后的变量值

https://leetcode.cn/problems/final-value-of-variable-after-performing-operations/description/

int finalValueAfterOperations(char** operations, int operationsSize) {
    int x = 0;

    for(int i = 0; i < operationsSize; ++i) {
        if(operations[i][1] == '-') --x;
        else ++x;
    }
    return x;
}
  • 13
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

子琦啊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值