一些力扣简单编程题的C语言解法

张开发
2026/4/18 8:31:59 15 分钟阅读

分享文章

一些力扣简单编程题的C语言解法
https://leetcode.cn/problems/longest-common-prefix/description/最长公共前缀#include stdlib.h #include stdbool.h char* longestCommonPrefix(char** strs, int strsSize) { char * result (char*) malloc (200 * sizeof(char)); bool resultFound false; int j 0; while (resultFound false) { result[j] strs[0][j]; if (result[j] \0) { resultFound true; break; } for (int i 1; i strsSize; i) { if (strs[i][j] ! result[j]) { resultFound true; result[j] \0; break; }; }; j; } return result; }https://leetcode.cn/problems/roman-to-integer/罗马数字转整数int romanToInt(char* s) { int result 0; for (int i 0; s[i] ! \0; i) { switch (s[i]) { case I: if (s[i 1] V) { result 4; i; break; } if (s[i 1] X) { result 9; i; break; } result 1; break; case V: result 5; break; case X: if (s[i 1] L) { result 40; i; break; } if (s[i 1] C) { result 90; i; break; } result 10; break; case L: result 50; break; case C: if (s[i 1] D) { result 400; i; break; } if (s[i 1] M) { result 900; i; break; } result 100; break; case D: result 500; break; case M: result 1000; break; default: break; }; }; return result; }https://leetcode.cn/problems/minimum-distance-to-the-target-element/description/到目标元素的最小距离#include stdbool.h getMinDistance(int* nums, int numsSize, int target, int start) { int i start; int j start; while (true) { if (i 0 i numsSize){ if (nums[i] target) return start - i; }; if (j 0 j numsSize){ if(nums[j] target) return j - start; }; i--; j; }; }https://leetcode.cn/problems/palindrome-number/回文数#include stdbool.h bool isPalindrome(int x) { int tempX[10] {0}; int xLength 0; if (x 0) return false; while (x 10) { tempX[xLength] x % 10; xLength; x x/10; }; tempX[xLength] x; for (int i 0; i xLength; i) { if (tempX[i] ! tempX[xLength]) return false; xLength--; }; return true; }

更多文章