88.Merge Sorted Array
题目链接:
题目描述:
给定两个有序数组,将两个数组合并。
题目分析:
因为两个数组大小给定了,可以用尾插法。
代码:
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int iM=m-1,iN=n-1,cur=m+n-1;
while(iM>=0 && iN>=0){
nums1[cur--]=nums1[iM]>nums2[iN]? nums1[iM--]:nums2[iN--];
}
while(iN>=0){
nums1[cur--]=nums2[iN--];
}
}
};
125. Valid Palindrome
题目链接:
题目描述:
判断字符串是否是回文。
For example,
“A man, a plan, a canal: Panama” is a palindrome.
“race a car” is not a palindrome.
题目分析:
比较麻烦的是字符串中的非字母和数字的处理。
代码:
class Solution {
public:
bool isAlphanumeric(char ch){
if((ch>='a' && ch<='z') || (ch>='A' && ch<='Z') || (ch>='0' && ch<='9')){
return true;
}
return false;
}
bool isPalindrome(string s) {
int high=s.size()-1;
int low=0;
bool flag=true;
while(low<high){
flag=true;
if(!isAlphanumeric(s[low])){
low++;
flag=false;
}
if(!isAlphanumeric(s[high])){
flag=false;
high--;
}
if(flag){
s[low]=tolower(s[low]);
s[high]=tolower(s[high]);
if(s[low]!=s[high]){
return false;
}
low++;
high--;
}
}
return true;
}
};
28. Implement strStr()
题目链接:
题目描述:
找出子串在主串第一次出现的下标索引。
题目分析:
朴素模式匹配算法。
代码:
class Solution {
public:
int strStr(string haystack, string needle) {
int lenH=haystack.size();
int lenN=needle.size();
int i=0,j=0;
while(i<lenH &&j<lenN){
if(haystack[i]==needle[j]){
i++;
j++;
}
else{
i=i-j+1;
j=0;
}
}
if(j>=lenN){
return i-j;
}
else{
return -1;
}
}
};