力扣每日一题 检查两个字符串数组是否相等

Day 34

Date: November 1, 2022 8:51 AM
LinkedIn: https://leetcode.cn/problems/check-if-two-string-arrays-are-equivalent/description/
Title: 检查两个字符串数组是否相等

class Solution:
    def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
        str1 = ''.join(word1)
        str2 = ''.join(word2)

        return str1 == str2

拼接列表字符串

  • 字符串=‘分隔符’.join(列表)

    • 如:
    words=['a','b','c']
    str1=' '.join(words)
    print(str1)
    # a b c
    
    words=['a','b','c']
    str1=''.join(words)
    print(str1)
    # abc
    
在 C 语言中,给定两个无序整数数组 A 和 B,要找到它们的交集,可以使用哈希集合(如标准库中的 `std::unordered_set` 或自定义的散列表结构)来解决这个问题。以下是基本步骤: 1. 创建一个空的哈希集合(集合不会包含重复元素)。 2. 遍历数组 A,将每个元素添加到集合中。 3. 再次遍历数组 B,对于集合中已存在的元素(即存在于数组 A 中),记录下来。 4. 返回收集到的所有共同元素。 下面是一个简单的示例代码片段: ```c #include <stdio.h> #include <stdlib.h> #define MAX_SIZE 100 typedef struct Node { int data; struct Node* next; } Node; // 自定义链表辅助函数 Node* createSet(int arr[], int n) { Node* head = NULL; for (int i = 0; i < n; i++) { if (!head) { head = (Node*)malloc(sizeof(Node)); head->data = arr[i]; head->next = NULL; } else { Node* temp = head; while (temp->next != NULL && arr[i] > temp->next->data) temp = temp->next; if (arr[i] <= temp->next->data) continue; Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = arr[i]; newNode->next = temp->next; temp->next = newNode; } } return head; } int* intersect(int* nums1, int m, int* nums2, int n) { Node* set = createSet(nums1, m); int intersection[MAX_SIZE] = {0}; int count = 0; for (int i = 0; i < n; i++) { if (find(set, nums2[i])) { intersection[count++] = nums2[i]; } } // 如果没有任何交集,返回空指针 if (count == 0) return NULL; // 缩小结果数组大小并返回 intersection[count] = 0; return intersection; } // 查找链表中是否存在指定值 int find(Node* head, int value) { while (head != NULL && head->data != value) head = head->next; return head != NULL; } void printArray(int arr[], int size) { Node* temp = arr; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } printf("\n"); } int main() { int nums1[] = {1, 2, 2, 1}; // 示例数组 A int nums2[] = {2, 2}; // 示例数组 B int m = sizeof(nums1) / sizeof(nums1[0]); int n = sizeof(nums2) / sizeof(nums2[0]); int* result = intersect(nums1, m, nums2, n); if (result) { printf("Intersection: "); printArray(result, count); } else { printf("No common elements.\n"); } free(result); // 释放内存 return 0; } ``` 在这个例子中,我们首先创建了一个链表表示数组 A 的唯一元素,然后遍历数组 B,查找链表中存在的元素,并将它们存入新数组 `intersection`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

只惠摸鱼

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

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

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

打赏作者

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

抵扣说明:

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

余额充值