编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
char* longestCommonPrefix(char** strs, int strsSize) {
char* s=strs[0];
for(int j =0;s[j];j++)
{
for(int i =0;i<strsSize;i++)
{
if(strs[i][j]!=s[j])
{
s[j]='\0';
return s;
}
}
}
return s;
}
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
每个右括号都有一个对应的相同类型的左括号
char duiying(char s)
{
if(s=='}')
{
return '{';
}
if(s == ']')
{
return '[';
}
if(s ==')')
{
return '(';
}
return 0;
}
bool isValid(char* s) {
int n = strlen(s);
if(n%2==1)//输入的数必须为偶数
{
return 0;
}
char arr[n+1];
int top = 0;
for(int i = 0;i<n;i++)
{
char ch = duiying(s[i]);
if(ch)
{
if(top==0||arr[top-1]!=ch)
{
return 0;
}
top--;
}
else
{
if(i==(n-1))//若最后一个使ch=0则会为正错,防止错误
{
return 0;
}
arr[top] =s[i];
top++;
if(top>(n/2))//若top一直加到超多一半,因为对称性,错误
{
return 0;
}
}
}
return 1;
}
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。
你可以按任意顺序返回答案。
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
for(int i = 0;i<numsSize-1;i++)
{
for(int j =i + 1 ;j<numsSize;j++)
{
if(nums[i]+nums[j]==target)
{
int* ret = malloc(sizeof(int) * 2);
ret[0] = i , ret[1] = j;
*returnSize = 2;
return ret;
}
}
}
*returnSize = 0;
return NULL;
}
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数
是指正序(从左向右)和倒序(从右向左)读都是一样的整数
bool isPalindrome(int x) {
int round1 = 0;
int round2 = 0;
if(x < 0 || x%10==0&&x!=0)
{
return false;
}
else
{
while(round2<x)
{
round1 = x%10;
round2 = round2*10+round1;
x = x/10;
}
if(round2 == x)
{
return true;
}
else
{
if(round2/10==x)
{
return true;
}
else
{
return false;
}
}
}
}
罗马数字转整数
int romanToInt(char* s) {
int num = 0;
int i = 0;
while (*(s + i) != '\0')
{
if (*(s + i) == 'C' && *(s + i + 1) == 'D')
{
num = num + 400;
i += 2;
}
else if(*(s+i)=='X'&&*(s+i+1)=='L')
{
num+=40;
i+=2;
}
else if (*(s + i) == 'C' && *(s + i + 1) == 'M')
{
num += 900;
i += 2;
}
else if (*(s + i) == 'I' && *(s + i + 1) == 'V')
{
num = num + 4;
i += 2;
}
else if (*(s + i) == 'I' && *(s + i + 1) == 'X')
{
num += 9;
i += 2;
}
else if (*(s + i) == 'X' && *(s + i + 1) == 'C')
{
num += 90;
i += 2;
}
else if (*(s + i) == 'I')
{
num = num + 1;
i++;
}
else if (*(s + i) == 'V')
{
num = num + 5;
i++;
}
else if (*(s + i) == 'X')
{
num = num + 10;
i++;
}
else if (*(s + i) == 'L')
{
num += 50;
i++;
}
else if (*(s + i) == 'C')
{
num = num + 100;
i++;
}
else if (*(s + i) == 'D')
{
num = num + 500;
i++;
}
else if (*(s + i) == 'M')
{
num = num + 1000;
i++;
}
}
return num;
}
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
struct ListNode a = {};
struct ListNode* ar = &a;
while(list1&&list2)
{
if(list1->val<list2->val)
{
ar->next = list1;
list1 = list1->next;
}
else
{
ar->next = list2;
list2 = list2->next;
}
ar = ar->next;
}
ar->next = list1?list1:list2;
return a.next;
}