摘要:
算法1。动态规划dp[i][j] 表示的是 从i 到 j 的字串,是否是回文串。则根据回文的规则我们可以知道:如果s[i] == s[j] 那么是否是回文决定于 dp[i+1][ j - 1]当 s[i] != s[j] 的时候, dp[i][j] 直接就是 false。动态规划的进行是按照字符串的长度从1 到 n推进的。代码很明晰:给出java代码,复杂度 O(n^2)public class Solution { boolean[][] dp; public String longestPalindrome(String s) { if(s.length() == 0) ... 阅读全文
摘要:
注意数组定义在leetcode里面必须指定长度。class Solution {public:char a[8]="MDCLXVI";int b[7]={1000,500,100,50,10,5,1}; int romanToInt(string s) { int k=0; int j=0; int i=0; for(;i<=6;i++) { if(i%2==0) { if(s[j]==a[i]) { ... 阅读全文
摘要:
class Solution {public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int>output; int i,j; for(i=0;i<numbers.size()-1;i++) { for(j=numbers.size()-1;j>i;j--) { if(numbers[i]+numbers[j]==target) { ... 阅读全文
摘要:
class Solution {public:vector<int>v1;vector<vector<int>>v; vector<vector<int> > permuteUnique(vector<int> &num) { v.clear(); sort(num.begin(),num.end()); backtrace(0,num); return v; } void backtrace(int depth,vector<int> &num) { if(depth==nu... 阅读全文
摘要:
合并排序后的数组从长数组的尾部开始合并,时间复杂度O(m+n),空间复杂度O(1)class Solution {public: void merge(int A[], int m, int B[], int n) { int i=m-1; int j=n-1; int k=m+n-1; while(i>=0&&j>=0) { if(A[i]>B[j]) A[k--]=A[i--]; else A[k--]=... 阅读全文
摘要:
合并排序后的数组方法:从长数组的尾部开始,可以时间复杂度O(m+n),空间复杂度O(1)class Solution {public: void merge(int A[], int m, int B[], int n) { int i=m-1; int j=n-1; int k=m+n-1; while(i>=0&&j>=0) { if(A[i]>B[j]) A[k--]=A[i--]; else A[k-... 阅读全文
摘要:
题目不难,边界情况很多class Solution {public: int lengthOfLastWord(const char *s) { const char *s1=s+strlen(s)-1;; int i=0; while(*s1==' ')//结尾有空格 s1--; while(*s1!=' '&&s1>=s)//不含空格的情况 { i++; s1--; } return i; ... 阅读全文
摘要:
class Solution {public: vector<int> plusOne(vector<int> &digits) { reverse(digits.begin(),digits.end()); int s=digits[0]+1; int carry=0; if(s>=10)carry=1; else digits[0]=s; if(carry) { for(int i=0;i<digits.size();i++) { ... 阅读全文
摘要:
Rotate Listclass Solution {public: ListNode *rotateRight(ListNode *head, int k) { if(head==NULL)return NULL; ListNode *p=head; int n=0; while(p->next) { p=p->next; n++; } n++; k=k%n; p->next=head; ListN... 阅读全文
摘要:
Merge Intervals合并区间/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ bool comp(const Interval &a, const Interval &b){ if(a.start==b.start)return a.end<b.end; ... 阅读全文