C++数据结构-string

功能例子
初始化string s; //空串
string s(“12345asdf”);
取他的子串tmp = s.substr(i, wlen); //入参1,start位置;
入参2可选,长度
大小cout << s.length() << endl;
cout << s.size() << endl;
添加ret.push_back(tmp);
删除tmp.pop_back();
查找int pos=haystack.find(needle); //类似C语言的strstr,可以直接返回具体下标
查看最后一个元素tmp.back()
基本判断isalnum–数字和字母
isdigit–数字 isalpha–字母
islower–小写 isupper–大写
 6. 函数入参
string s = "1";
Change(s);
void Change(string &s)  //声明

 7. 大小写和数字
transform(s.begin(),s.end(),s.begin(),::tolower);
//Applies op to each of the elements in the range [first1,last1) 
//and stores the value returned by each operation in the range that begins at result.
int op_increase (int i) { return ++i; }
transform (foo.begin(), foo.end(), bar.begin(), op_increase);

8. 字符串扩充&整形转换为字符串
class Solution {
public:
    static int cmp(int a, int b) {
        string sa = to_string(a);
        string sb = to_string(b);
        return sa+sb>sb+sa;
    }
    string largestNumber(vector<int>& nums) {
        sort(nums.begin(),nums.end(), cmp);
        string s;
        char tmp[10];
        for (int val:nums) {
            s+=to_string(val);
        }
        return s;
    }
};
 

leetcode38题

class Solution {
public:
    string countAndSay(int n) {
        string s = "1";
        while(--n) {
            Change(s);
        }
        return s;
    }
    void Change(string &s) {
        string tmp;
        int count = 1;
        for(int i = 1; i <= s.size(); i++) {
            if(i != s.size() && s[i] == s[i-1]){
                count++;
            } else {
                tmp.push_back(count+'0');
                tmp.push_back(s[i-1]);
                count = 1;
            }
        }
        s = tmp;
    } 
};

leetcode242

class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.length() != t.length()) {
            return false;
        }
        unordered_map<int, int> hash;
        for (char ch: s) {
            hash[ch]++;
        }
        for (char ch: t) {
            hash[ch]--;
            if(hash[ch] < 0) {
                return false;
            }
        }
        return true;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值