字符串类型题
Posted zpcoding
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字符串类型题相关的知识,希望对你有一定的参考价值。
1,Vaild Palindrome
1 bool isPalindrome(string& s) { 2 transform(s.begin(), s.end(), s.begin(), tolower); // 把字符全部转换成小写 3 int left = 0; 4 int right = s.length()-1; 5 while (left < right) { 6 if (!isalnum(s[left])) ++left; 7 else if (!isalnum(s[right])) --right; 8 else if (s[left] != s[right]) return false; 9 else { 10 ++left; 11 --right; 12 } 13 } 14 return true; 15 }
2,Implement strStr
1 int strStr(const string& haystack, const string& needle) { // KMP 算法,BM 算法 2 if (needle.empty()) return 0; 3 const int N = haystack.length() - needle.length(); 4 for (int i = 0; i <= N; ++i) { 5 int j = i; // 源串索引 6 int k = 0; // 字串索引 7 while (haystack[j] == needle[k] && j < haystack.length() && k < needle.length()) { 8 ++j; 9 ++k; 10 } 11 if (k == needle.length()) return i; 12 } 13 return -1; 14 }
3,String to Integer(atoi)
1 int myAtoi(const string& str) { 2 const int n = str.length(); 3 int sign = 1; 4 int i = 0; 5 int num = 0; 6 7 while (str[i] == ‘ ‘ && i < n) ++i; // 前面的字符处理 8 if (str[i] == ‘+‘) { 9 sign = 1; 10 ++i; 11 } 12 else if (str[i] == ‘-‘) { 13 sign = -1; 14 ++i; 15 } 16 for (; i < n; ++i) { 17 if (str[i] < ‘0‘ || str[i] > ‘9‘) 18 break; 19 num = num * 10 + str[i] - ‘0‘; 20 21 if (sign == 1 && num > INT_MAX) 22 return INT_MAX; 23 else if (sign == -1 && num > INT_MIN + 1) 24 return INT_MIN; 25 } 26 return sign * num; 27 }
4,Add Binary
1 string addBinary(string a, string b) { // 思路同 Add Binary(链表类型题) plusOne(数组类型题) 2 string result; 3 int carry = 0; 4 reverse(a.begin(), a.end()); // 先反转两个数组,从低位开始相加 5 reverse(b.begin(), b.end()); 6 const int n = a.length() > b.length() ? a.length() : b.length(); 7 for (int i = 0; i < n; ++i) { 8 const int ai = i < a.length() ? a[i]-‘0‘ : 0; 9 const int bi = i < b.length() ? b[i]-‘0‘ : 0; 10 int value = (ai + bi + carry) % 2; 11 carry = (ai + bi + carry) / 2; 12 result.insert(result.begin(), value + ‘0‘); 13 } 14 if (carry == 1) 15 result.insert(result.begin(), ‘1‘); 16 return result; 17 }
5,Longest Palindromic Substring(未实现)
6,Regular Expression Matching
1 bool isMatchI(const char *s, const char *p) { //递归版 有挑战的一道题目 2 if (*p == ‘