[打卡]字符串操作(二)

剑指offer:替换空格

请实现一个函数,把字符串 s 中的每个空格替换成"%20"。

示例:
输入:s = "We are happy."
输出:"We%20are%20happy."

解题思路:先统计出现空格次数,每出现一次空格需要将字符串的大小扩容2,再从字符串末开始在空格处替换"%20"。

class Solution {
public:
    string replaceSpace(string s) {
        int count = 0, len = s.size();
        for(char c : s){
            if(c == ' ') count++;
        } 
        s.resize(len + 2 * count);
        for(int i = len - 1,j = s.size() - 1; i < j; i--,j--){
            if(s[i] != ' '){
                s[j] = s[i];
            }else{
                s[j - 2] = '%';
                s[j - 1] = '2';
                s[j] = '0';
                j-=2;
            }
        }
        return s;
    }
};

稀疏数组搜索

稀疏数组搜索。有个排好序的字符串数组,其中散布着一些空字符串,编写一种方法,找出给定字符串的位置。

示例1:
 输入: words = ["at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""], s = "ta"
 输出:-1
 说明: 不存在返回-1。
 
示例2:
 输入:words = ["at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""], s = "ball"
 输出:4

解题思路:可以直接使用for循环直接遍历得到结果,但是得知题意是一个有序的字符串数组,那我们就还可以使用二分查找。

// for循环
class Solution {
public:
    int findString(vector<string>& words, string s) {
        for(int i=0; i<words.size(); i++) {
            if(s == words[i]) return i;
        }
        return -1;
    }
};
// 二分查找
class Solution {
public:
    int findString(vector<string>& words, string s) {
        int l = 0, r = words.size() - 1;
        while(l <= r){
            int mid = (l + r) / 2;
            while(mid > l && words[mid].empty()) mid--;
            if(words[mid] == s) return mid;
            else if(words[mid] > s) r = mid - 1;
            else l = mid + 1;
        }
        return -1;
    }
};

单词规律

给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。

这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。

示例1:
 输入: pattern = "abba", str = "dog cat cat dog"
 输出: true
	
示例 2:
 输入:pattern = "abba", str = "dog cat cat fish"
 输出: false

示例 3:
 输入: pattern = "aaaa", str = "dog cat cat dog"
 输出: false
class Solution {
public:
    bool wordPattern(string pattern, string str) {
        unordered_map<string, char> str2ch;
        unordered_map<char, string> ch2str;
        int m = str.length();
        int i = 0;
        for (auto ch : pattern) {
            if (i >= m) {
                return false;
            }
            int j = i;
            while (j < m && str[j] != ' ') j++;
            const string &tmp = str.substr(i, j - i);
            if (str2ch.count(tmp) && str2ch[tmp] != ch) {
                return false;
            }
            if (ch2str.count(ch) && ch2str[ch] != tmp) {
                return false;
            }
            str2ch[tmp] = ch;
            ch2str[ch] = tmp;
            i = j + 1;
        }
        return i >= m;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值