14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string
""
.
Example 1:
Input: ["flower","flow","flight"] Output: "fl"
Example 2:
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters
a-z
.
//Solution
//总结:返回指针类型,通过遍历比较,保留最长的子串即可。
char * longestCommonPrefix(char ** strs, int strsSize){
char* temp;
if(strsSize <=0 ) return "";
temp = strs[0];
for( int i = 0;i<strsSize;i++)
{
int j = 0;
while(temp[j]&&strs[i][j] && temp[j]==strs[i][j]) j++;
temp[j] = 0;
}
return temp;
}
20. Valid Parentheses
Given a string containing just the characters
'('
,')'
,'{'
,'}'
,'['
and']'
, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()" Output: true
Example 2:
Input: "()[]{}" Output: true
Example 3:
Input: "(]" Output: false
Example 4:
Input: "([)]" Output: false
Example 5:
Input: "{[]}" Output: true
//Solution
//总结:用堆栈,后入先出
bool isValid(char * s){
int stack[10005] ={0};
int top = 0;
while(*s)
{
if(*s == '(')
stack[top++] = *s + 1; //'('+1 = ')'
else if(*s == '[' || *s == '{')
stack[top++] = *s + 2;//类似上面
else if(top == 0)
return false;
else if(stack[top - 1] == *s)
top--;
else
return false;
s++;
}
return top ==0;
}
21. Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
//Solution
//总结:先找到头并保存,用于返回;之后遍历比较就行
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
struct ListNode* head;
struct ListNode* res;//返回的是头,先找头
if(!l1) return l2;
if(!l2) return l1;
if(l1->val <=l2->val)
{
head = l1;
l1 = l1->next;
}else{
head = l2;
l2 = l2->next;
}
res = head;//保存头
while(l1 && l2)
{
if(l1->val < l2->val)
{
head->next = l1;
l1 = l1->next;//指向下一个元素
}
else
{
head->next = l2;
l2 = l2->next;
}
head->next->next = NULL;//清空下下一个节点
head = head->next;//移向新增加的节点
}
if(l1)
{
head->next = l1;
}
else if(l2){
head->next = l2;
}
return res;
}