• 【leetcode】两句话中的不常见单词 c++


    题目描述:

    句子 是一串由空格分隔的单词。每个 单词 仅由小写字母组成。

    如果某个单词在其中一个句子中恰好出现一次,在另一个句子中却 没有出现 ,那么这个单词就是 不常见的 。

    给你两个 句子 s1 和 s2 ,返回所有 不常用单词 的列表。返回列表中单词可以按 任意顺序 组织。

    示例 1:

    输入:s1 = “this apple is sweet”, s2 = “this apple is sour”
    输出:[“sweet”,“sour”]

    示例 2:

    输入:s1 = “apple apple”, s2 = “banana”
    输出:[“banana”]

    提示:

    1 <= s1.length, s2.length <= 200
    s1 和 s2 由小写英文字母和空格组成
    s1 和 s2 都不含前导或尾随空格
    s1 和 s2 中的所有单词间均由单个空格分隔

    c++代码:

     class Solution {
    public:
        vector<string> uncommonFromSentences(string s1, string s2) {
            int n1=s1.length(),n2=s2.length(),start=0;
            vector<string> v;
            map<string,int> m1,m2;
            for(int i=start;i<n1;i++){  
                if(s1[i]==' '){
                    string word = s1.substr(start,(i-1)-(start)+1);
                    start=i+1;
                    m1[word]+=1;
                }
                if(s1[i]!=' '&&i==n1-1){
                    string word = s1.substr(start);
                    m1[word]+=1;
                }
            }
            start=0;
            for(int i=start;i<n2;i++){  
                if(s2[i]==' '){
                    string word = s2.substr(start,(i-1)-(start)+1);
                    start=i+1;
                    m2[word]+=1;
                }
                if(s2[i]!=' '&&i==n2-1){
                    string word = s2.substr(start);
                    m2[word]+=1;
                }
            }
            for(auto it=m1.begin();it!=m1.end();it++){
                if(it->second==1&&m2[it->first]==0)v.push_back(it->first);
            }
            for(auto it=m2.begin();it!=m2.end();it++){
                if(it->second==1&&m1[it->first]==0)v.push_back(it->first);
            }
            return v;
        }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    在这里插入图片描述

    总结:

    字符串截取函数:s.substr(pos,len):返回字符串s从pos位置开始,长度为len的子串。

  • 相关阅读:
    Vue学习之计算属性
    通过easyexcel导出数据到excel表格
    对象中的字段隐藏
    SMARTPHONE PLATFORM st解决方案
    SpringBoot整合数据库连接
    单词猎手游戏
    基础 | 并发编程 - [ThreadLocal]
    Vue获取url路由地址、参数
    图像对比算法有哪些,图像对比算法是什么
    GB28181学习(六)——实时视音频点播(数据传输部分)
  • 原文地址:https://blog.csdn.net/qq_40315080/article/details/126197958