个人学习编程(3-27) leetcode刷题
合并两个有序链表:
当我们执行
current->next = node;
时,current
最初指向的是dummy
节点,因此这行代码实际上是:dummy->next = node;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
dummy->next = NULL;
struct ListNode* current = dummy;
// 遍历两个链表
while(list1 != NULL && list2 != NULL){
if(list1->val <= list2->val){
current->next = list1;
list1 = list1->next;
}
else{
current->next = list2;
list2 = list2->next;
}
current = current->next;
}
// 如果还有剩余的节点,直接连接到合并链表的末尾
if (list1 != NULL) {
current->next = list1;
} else {
current->next = list2;
}
// 返回合并后的链表(跳过虚拟头节点)
struct ListNode* mergedList = dummy->next;
free(dummy); // 释放虚拟头节点
return mergedList;
}
找出最长公共前缀:
char* longestCommonPrefix(char** strs, int strsSize) {
if (strsSize == 0) return ""; // 如果数组为空,返回空字符串
// 假设第一个字符串是公共前缀
char *prefix = strs[0];
// 遍历其他字符串
for (int i = 1; i < strsSize; i++) {
// 比较当前的 prefix 和 strs[i]
while (strs[i] != prefix && strncmp(prefix, strs[i], strlen(prefix)) != 0) {
// 缩短 prefix,直到找到公共前缀
prefix[strlen(prefix) - 1] = '\0';
}
}
return prefix; // 返回最长公共前缀
}
找出字符串中第一个匹配项的下标:
示例 1:
输入:haystack = "sadbutsad", needle = "sad" 输出:0 解释:"sad" 在下标 0 和 6 处匹配。 第一个匹配项的下标是 0 ,所以返回 0 。示例 2:
输入:haystack = "leetcode", needle = "leeto" 输出:-1 解释:"leeto" 没有在 "leetcode" 中出现,所以返回 -1 。
int strStr(char* haystack, char* needle) {
if(*needle == '\0'){
return 0;
}
int i = 0; //haystack
int j = 0; //needle
//遍历haystack
while(haystack[i] != '\0'){
//haystack[i] 和 needle[j]匹配时,继续像后匹配
if(haystack[i] == needle[j]) {
j++;
//如果needle匹配完成,返回匹配位置
if(needle[j] == '\0'){
return i - j + 1;
}
} else {
i -= j - 1;
j = 0;
}
i++;
}
return -1;
//如果找不到匹配项,返回-1
}