今日份 leetcode
- 1768. 交替合并字符串
- 1678. 设计 Goal 解析器
- 389. 找不同
![]()
1768. 交替合并字符串
解题思路
先轮流往新字符串里加字符,有多的再全部补上,结尾以 \0 结束字符串
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| char * mergeAlternately(char * word1, char * word2){ int len1 = strlen(word1); int len2 = strlen(word2); char * res = (char *) malloc (sizeof(char) * (len1 + len2 + 1)); int residx = 0; int idx1 = 0; int idx2 = 0; while(idx1 < len1 && idx2 < len2){ res[residx++] = word1[idx1++]; res[residx++] = word2[idx2++]; } while(idx1 < len1) res[residx++] = word1[idx1++]; while(idx2 < len2) res[residx++] = word2[idx2++]; res[residx] = '\0'; return res; }
|
1678. 设计 Goal 解析器
解题思路
已知输入的字符串只会包含 G、() 和 (al),所以只需要知道是不是 G 还有知道 ( 后面跟的是什么就行了,然后往新字符串中加入对应值,遍历到其他字符的情况就跳过,最后补上 \0 结束字符串
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| char * interpret(char * command){ int reslen = strlen(command); char * res = (char *) malloc (sizeof(char) * reslen + 1); int idx = 0; for (int i = 0; i < reslen; i++){ if(command[i] == 'G') res[idx++] = 'G'; if(command[i] == '('){ if(command[i + 1] == ')') res[idx++] = 'o'; if(command[i + 1] == 'a') { res[idx++] = 'a'; res[idx++] = 'l'; } } } res[idx] = '\0'; return res; }
|
389. 找不同
![image.png]()
解题思路
统计每个字符出现的次数,然后找出次数不一样的将它返回就行
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| char findTheDifference(char * s, char * t){ int len = strlen(s); int idx = 0; int s_flags[26] = {0}; int t_flags[26] = {0}; for(int i = 0; i < len; i++){ s_flags[s[i] - 'a']++; t_flags[t[i] - 'a']++; } t_flags[t[len] - 'a']++; for(int i = 0; i < 26; i++){ if(s_flags[i] != t_flags[i]){ idx = i; break; } } return idx + 'a'; }
|