leetcode 字符串类型题

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 }
isPalindrome

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 }
strStr

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 }
myAtoi

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 }
addBinary

5,Longest Palindromic Substring(动态规划)

int handler(string& s) {
    int len = s.length();
    int maxLen = INT_MIN;
    //dp[i][j] 表示 s[i:j] 的字符串是否是回文字符串
    vector<vector<bool>> dp(len, vector<bool>(len, false));
    if(len == 0 || len == 1) return len;

    for(int j=0; j<len; j++) {  // 竖着初始化,初始化矩阵的上三角
        for(int i=0; i<=j; i++) {
            if(j - i < 2)
                dp[i][j] = s[i] == s[j];
            else
                //判断 dp[i][j] 的左下角的元素 dp[i+1][j-1]
                dp[i][j] = dp[i+1][j-1] && s[i] == s[j];
            //取最大长度
            if(dp[i][j] && j-i+1 > maxLen)
                maxLen = max(maxLen, j-i+1);
        }
    }
    return maxLen;
}
Longest Parlindromic Substring

6,Regular Expression Matching

 1 bool isMatchI(const char *s, const char *p) {   //递归版   有挑战的一道题目
 2     if (*p == '\0') return *s == '\0';
 3 
 4     //next char is not '*',then match current character
 5     if (*(p + 1) != '*') {
 6         if (*p == *s || (*p == '.' && *s != '\0')) { // correctly match
 7             return isMatchI(s + 1, p + 1);
 8         }
 9         else {                                      // failed match
10             return false;
11         }
12     }
13     else {                                           // next char is '*'
14         while (*p == *s || (*p == '.' && *s != '\0')) {
15             if (isMatchI(s, p + 2)) {
16                 return true;
17             }
18             s++;
19         }
20         return isMatchI(s, p + 2);
21     }
22 }
isMatch

7,Wildcard Matching

 1 bool isMatchII1(const char *s, const char *p) {  // 递归版
 2     if (*p == '*') {
 3         while (*p == '*') ++p;  // skip continuous '*'
 4         if (*p == '\0') return true;
 5         while (*s != '\0' && !isMatchII1(s, p)) ++s;
 6 
 7         return *s != '\0';
 8     }
 9     else if (*p == '\0' || *s == '\0')
10         return *p == *s;
11     else if (*p == *s || *p == '?')
12         return isMatchII1(++s, ++p);
13     else
14         return false;
15 }
16 bool isMatchII2(const char *s, const char *p) {  // 迭代版
17     bool star = false;
18     const char *str = s;  // str 可以变,*str 不能变
19     const char *ptr = p;
20 
21     while (*str != '\0') {
22         switch (*ptr) {
23         case '?':
24             str++;
25             ptr++;
26             break;
27         case '*':
28             star = true;
29             while (*ptr == '*') ++p;
30             if (*ptr == '\0') return true;
31             break;
32         default:
33             if (*str != *ptr) {
34                 if (!star) 
35                     return false;
36                 str++;
37             }
38         }
39     }
40     while (*ptr == '*') ++ptr;
41     return (*ptr == '\0');
42 
43 }
isMatch

8,Longest Common Prefix

 1 string longestCommonPrefix1(vector<string>& strs) {  // 纵向扫描
 2     if (strs.empty()) return "";
 3 
 4     for (int index = 0; index < strs[0].size(); ++index) {  // 选取第一个字符串和其它字符串进行比较
 5         for (int i = 1; i < strs.size(); ++i) {
 6             if (strs[i][index] != strs[0][index])
 7                 return strs[0].substr(0, index);
 8         }
 9     }
10     return strs[0];
11 }
12 
13 string longestCommonPrefix2(vector<string>& strs) { // 横向扫描
14     if (strs.empty()) return "";
15 
16     int right_most = strs[0].size() - 1;
17     for (size_t i = 1; i < strs.size(); ++i) {
18         for (int j = 0; j <= right_most; ++j) {
19             if (strs[i][j] != strs[0][j])
20                 right_most = j - 1;
21         }
22     }
23     return strs[0].substr(0, right_most + 1);
24 }
longestCommonPrefix

9,Valid Number

 1 bool isNumber(const char *s) {  // 
 2     char* endptr;
 3     strtod(s, &endptr);
 4     
 5     if (endptr == s)
 6         return false;
 7 
 8     for (; *endptr; ++endptr) {
 9         if (!isspace(*endptr))
10             return false;
11     }
12     return true;
13 }
isNumber

10,Integet to Roman

 1 string intToRoman1(int num) {
 2     const int radix[] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
 3     const string symbol[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
 4     
 5     string roman;
 6     for (size_t i = 0; num > 0; ++i) {
 7         int count = num / radix[i];
 8         num %= radix[i];
 9         for (; count > 0; --count)
10             roman += symbol[i];
11     }
12     return roman;
13 }
14 
15 string intToRoman2(int num) {
16     string res = "";
17     vector<int> val = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
18     vector<string> str = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
19     for (int i = 0; i < val.size(); ++i) {
20         while (num >= val[i]) {
21             num -= val[i];
22             res += str[i];
23         }
24     }
25     return res;
26 }
intToRoman

11,Roman to Integer

 1 int romanToInt(const string& s) {
 2     int result = 0;
 3     unordered_map<char, int> mapping;
 4     mapping['I'] = 1;
 5     mapping['V'] = 5;
 6     mapping['X'] = 10;
 7     mapping['L'] = 50;
 8     mapping['C'] = 100;
 9     mapping['D'] = 500;
10     mapping['M'] = 1000;
11 
12     for (size_t i = 0; i < s.size(); i++) {
13         if (i > 0 && (mapping[i] > mapping[i - 1])) {
14             result += (mapping[s[i]] - 2 * mapping[s[i - 1]]);
15         }
16         else {
17             result += mapping[s[i]];
18         }
19     }
20     return result;
21 }
romanToInt

12,Count and Say

 1 string getNext(const string& s) {
 2     stringstream ss;
 3     for (auto i = s.begin(); i != s.end();) {
 4         auto j = find_if(i, s.end(), bind1st(not_equal_to<char>(), *i));  // 需要看看函数怎么用
 5         ss << distance(i, j) << *i;
 6         i = j;
 7     }
 8     return ss.str();
 9 }
10 
11 string countAndSay(int n) {
12     string s("1");
13     while (--n) {
14         s = getNext(s);
15     }
16     return s;
17 }
countAndSay

13,Anagrams(回文构词法)

 1 vector<string> anagrams(vector<string>& strs) {
 2     unordered_map<string, vector<string>> group;
 3     for ( auto s = strs.begin(); s != strs.end();++s) {
 4         string key = *s;
 5         sort(key.begin(), key.end());  // 会修改原数据
 6         group[key].push_back(*s);
 7     }
 8     vector<string> result;
 9     for (auto it = group.cbegin(); it != group.cend(); ++it) {
10         if (it->second.size() > 1)
11             result.insert(result.end(), it->second.begin(), it->second.end());
12     }
13     return result;
14 }
anagrams

14,Simplify Path

 1 string simplifyPath(const string& path) {
 2     string dir;  
 3     stack<string> stk;
 4     string result;
 5 
 6     for (auto i = path.begin(); i != path.end();) {
 7         ++i;
 8         auto j = find(i, path.end(), '/');
 9         dir = string(i, j);   /*  获取两个 / / 之间的内容 */
10 
11         if (!dir.empty() && dir !="/" && dir != ".") {
12             if (dir == "..") {
13                 if (!stk.empty())
14                     stk.pop();
15             }
16             else
17                 stk.push(dir);
18         }
19         i = j;
20     }
21     //stringstream out;  // 可以用字符串流保存,然后通过 out.str() 转化成字符串返回
22     if (stk.empty())
23         //out << "/";
24         result = "/";
25     else {
26         while (!stk.empty()) {
27             string s = stk.top();
28             stk.pop();
29             //out << '/' << s;
30             result += "/" + s;
31         }
32     }
33     // return out.str();
34     return result;
35 }
simplifyPath

15,Length of Last Word

 1 int lengthOfLastWord1(const string& s) {  // STL::find_if,find_if_not,distance
 2     auto first = find_if(s.rbegin(), s.rend(), isalpha);
 3     auto last = find_if_not(first, s.rend(), isalpha);
 4     return distance(first, last);
 5 }
 6 
 7 int lengthOfLastWord2(const string& s) {
 8     int len = 0;
 9     for (int i = 0; i < s.length(); ++i) {
10         if (s[i] != ' ')
11             ++len;
12         else
13             len = 0;
14     }
15     return len;
16 }
lengthOfLastWord

 

c++常用函数

1, split

void split(string& s, vector<string>& v, char deli) {
    int current = 0, next = -1;
    do {
        current = next + 1;
        next = s.find_first_of(deli, current);
        v.push_back(s.substr(current, next - current));
    }while(next != -1);
}
split

 

以上题目来源于:http://www.github.com/soulmachine/leetcode

posted on 2019-03-01 16:55  爱笑的张飞  阅读(383)  评论(0编辑  收藏  举报

导航