LeetCode之双指针(1)
2016-01-06 10:34
357 查看
88.Merge Sorted Array
题目链接:https://leetcode.com/problems/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
题目链接:https://leetcode.com/problems/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()
题目链接:https://leetcode.com/problems/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; } } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解