leetcode重点分类(C语言) - 字符串

 分类参考:https://github.com/CyC2018/CS-Notes/blob/master/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E7%9B%AE%E5%BD%95.md

 

242. 有效的字母异位词

bool isAnagram(char* s, char* t)
{
    int x[26] = {0};
    int y[26] = {0};
    int m = strlen(s);
    int n = strlen(t);
    if(m != n) {
        return false;
    }
    for(int i = 0; i < m; i++) {
        x[s[i] - 'a']++;
        y[t[i] - 'a']++;
    } 
    for(int i = 0; i < 26; i++) {
        if(x[i] != y[i]) {
            return false;
        }
    }
    return true;
}

 

409. 最长回文串

int longestPalindrome(char* s)
{
    int lower[26] = {0};
    int high[26] = {0};
    int nums = 0;
    int index = 0;
    while (s[index] != '\0') {
        if (s[index] >= 'a' && s[index] <= 'z') {
            int i = s[index] - 'a';
            lower[i]++;
            nums = nums + lower[i] / 2 * 2;
            lower[i] = lower[i] % 2;
        }
        if (s[index] >= 'A' && s[index] <= 'Z') {
            int i = s[index] - 'A';
            high[i]++;
            nums = nums + high[i] / 2 * 2;
            high[i] = high[i] % 2;
        }
        ++index;
    }
    nums += ((index > nums) ? 1 : 0);
    return nums;
}

 

205. 同构字符串

bool isIsomorphic(char * s, char * t)
{
    int maps[128] = {0};
    int mapt[128] = {0};
    while (*s) {
        if (!maps[*s] && !mapt[*t]) {
            maps[*s] = *t;
            mapt[*t] = *s;
        }
        else if (maps[*s] != *t || mapt[*t] != *s) {
            return false;
        }
        s++;
        t++;
    }
    return true;
}

 

647. 回文子串

int cnt = 0;

void extendSubstrings(char* s, int start, int end)
{
    while (start >= 0 && end < strlen(s) && s[start] == s[end]) {
        start--;
        end++;
        cnt++;
    }
}

int countSubstrings(char* s)
{
    cnt = 0;
    for (int i = 0; i < strlen(s); i++) {
        extendSubstrings(s, i, i);
        extendSubstrings(s, i, i + 1);
    }
    return cnt;
}

 

9. 回文数

bool isPalindrome(int x)
{
    long long sum = 0;
    int temp = x;
    if (x < 0) {
        return false;
    }
    while(temp) {
        sum = sum * 10 + (temp % 10);
        temp = temp / 10;
    }
    return sum == x ? true : false;
}

 

696. 计数二进制子串

int countBinarySubstrings(char* s)
{
    int preLen = 0, curLen = 1, count = 0;
    for (int i = 1; i < strlen(s); i++) {
        if (s[i] == s[i - 1]) {
            curLen++;
        } else {
            preLen = curLen;
            curLen = 1;
        }
        if (preLen >= curLen) {
            count++;
        }
    }
    return count;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值