class Solution {
public:
bool isPalindrome(string s) {
transform(s.begin(), s.end(), s.begin(), ::tolower);
auto first = s.begin(), last = prev(s.end());
while(first < last){
if(!::isalnum(*first)) ++first;
else if(!::isalnum(*last)) --last;
else if(*first != *last) return false;
else {++first, --last;}
}
return true;
}
};
解法1:
class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.length(), n = needle.length();
if(!n) return 0;
for(int i = 0; i < m - n + 1; ++i){
int j = 0;
for(; j < n; ++j)
if(haystack[i + j] != needle[j])
break;
if(j == n)
return i;
}
return -1;
}
};
class Solution {
public:
string addBinary(string a, string b) {
string result;
const size_t n = a.size() > b.size() ? a.size() : b.size();
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int carry = 0;
for(size_t i = 0; i < n; ++i){
const int ai = i < a.size() ? a[i] - '0' : 0;
const int bi = i < b.size() ? b[i] - '0' : 0;
const int val = (ai + bi + carry) % 2;
carry = (ai + bi + carry) / 2;
result.insert(result.begin(), val + '0');
}
if(carry == 1)
result.insert(result.begin(), '1');
return result;
}
};
偷懒,用STL
class Solution {
public:
int lengthOfLastWord(string s) {
auto last = find_if(s.rbegin(), s.rend(), ::isalpha);
auto first = find_if_not(last, s.rend(), ::isalpha);
return distance(last, first);
}
};
题3.11
class Solution {
public:
int map(char c){
switch(c){
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return 0;
}
}
int romanToInt(string s) {
int result = 0;
for(size_t i = 0; i < s.size(); ++i){
if(i > 0 && map(s[i]) > map(s[i - 1]))
result += (map(s[i]) - 2 * map(s[i - 1]));
else
result += map(s[i]);
}
return result;
}
};