5. Longest Palindromic Substring
题目描述:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad"
Output: "bab
Note: “aba” is also a valid answer.
Example:
Input: "cbbd"
Output: "bb"
找到最长的回文子串。
考虑子串是奇偶的情况,根据代码优化原则,一般来说减少分支预测,可以加快速度,所以这里我把一个奇偶循环拆成了两个。最后速度超过66%的c++。
class Solution {
public:
string longestPalindrome(string s) {
int slen = s.length();
string res;
if(!slen) return res;
int max_cnt = 1;
res = s[0];
for(int i = 0; i < slen; i++) {
int ind1 = i, ind2 = i;
int cnt = -1;
while(1) {
if(s[ind1] == s[ind2]) cnt += 2;
else break;
ind1--; ind2++;
if(ind1 < 0 || ind2 >= slen) break;
}
if(cnt > max_cnt){
ind1 = ind1 + 1;
max_cnt = cnt; res = s.substr(ind1, max_cnt);
}
}
for(int i = 0; i < slen-1; i++) {
int ind1 = i, ind2 = i+1;
int cnt = 0;
while(1) {
if(s[ind1] == s[ind2]) cnt += 2;
else break;
ind1--; ind2++;
if(ind1 < 0 || ind2 >= slen) break;
}
if(cnt > max_cnt) {
ind1 = ind1 + 1;
max_cnt = cnt; res = s.substr(ind1, max_cnt);
}
}
return res;
}
};
获取子串的方法: string.substr(stt_point, num)
224. Basic Calculator
题目描述:
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .
You may assume that the given expression is always valid.
Some examples:
"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23
Note: Do not use the eval built-in library function.
代码实现:
372. Super Pow
在这里使用了一个数学知识:
ab % k = (a%k)(b%k)%k
举一个例子:
f(a,1234567) = f(a, 1234560) * f(a, 7) % k = f(f(a, 123456),10) * f(a,7)%k;
下面的代码是从leetcode的discussion看到的,写得非常清楚,而且写得很巧妙,令人赏心悦目。
class Solution {
private:
const int base = 1337;
int powmod(int a, int k) //a^k mod 1337 where 0 <= k <= 10
{
a %= base;
int result = 1;
for (int i = 0; i < k; ++i)
result = (result * a) % base;
return result;
}
public:
int superPow(int a, vector<int>& b) {
if (b.empty()) return 1;
int last_digit = b.back();
b.pop_back();
return powmod(superPow(a, b), 10) * powmod(a, last_digit) % base;
}
};
非递归的方式可以写成如下:
class Solution {
const int c = 1337;
public:
int superPow(int a, vector<int>& b) {
int r = 1;
a %= c;
for(int i=0;i<b.size();i++){
r = (powmod(r,10)*powmod(a,b[i]))%c;
}
return r;
}
private:
int powmod(int r,int k) {
int x = 1;
for(int i=1;i<=k;i++){
x = (x*r) % c;
}
return x;
}
};
参考链接:
https://discuss.leetcode.com/topic/50489/c-clean-and-short-solution