• C++ code:判断字符串相等


    如果两个字符串中0和1的个数分别相等,则称该对字符串为相等。

    方法一:

    由于string类对于读取文件中子串以及比较都很方便,所以,用string类的对象来逐对存放字串,然后将字串分别排序后对其进行比较是直接的思路。

     1 #include<iostream>
     2 #include<fstream>
     3 #include<algorithm>
     4 using namespace std;
     5 
     6 int main()
     7 {
     8     ifstream in("string.txt");
     9     for (string s, t; in >> s >> t;)
    10     {
    11         sort(s.begin(),s.end);
    12         sort(t.begin(),t.end);
    13         cout << (s==t?"yes
    ":"no
    ");
    14     }
    15 }

    程序中用到了算法sort调用,所以要包含算法库头文件algorithm。

    方法二:

    基本的排序算法需要对所有元素进行两重循环的操作,最快的排序算法也需要O(nlogn)数量级的运算次数,然而,如果仅对字串分别数一下1和0的个数,再比较其个数值,效率会更高:

     1 #include<iostream>
     2 #include<fstream>
     3 #include<algorithm>
     4 using namespace std;
     5 
     6 int main()
     7 {
     8     ifstream in("string.txt");
     9     for (string s, t; in >> s >> t;)
    10     {
    11         int sc1 = count(s.begin(), s.end(),'1');
    12         int sc0 = count(s.begin(), s.end(), '0');
    13         int tc1 = count(t.begin(), t.end(), '1');
    14         int tc0 = count(t.begin(), t.end(), '0');
    15         cout << (sc1==tc1&&sc0==tc0?"yes
    ":"no
    ");
    16     }
    17 }

    count计数也包含在C++标准库中,由于count算法只有一重循环的处理时间,虽然程序中有4次count调用,但比较排序算法,对于元素个数激增时,其效率能明显体现出来。当然有些读者可能看到了还能对其做进一步优化:count算法是线性的,无论如何,一重循环是不可避免的。

    方法三:

    根据问题描述,字串中非1即0, so,“0”的个数在总长度已知的情况下,可以不使用count算法,通过并列地判断总长度的相等性而直接得到:

     1 #include<iostream>
     2 #include<fstream>
     3 #include<algorithm>
     4 using namespace std;
     5 
     6 int main()
     7 {
     8     ifstream in("string.txt");
     9     for (string s, t; in >> s >> t;)
    10     {
    11         int s1 = count(s.begin(), s.end(), '1');
    12         int t1 = count(t.begin(), t.end(), '1');
    13         cout << (s1==t1&&s.length()==t.length()?"yes
    ":"no
    ");
    14     }
    15 }

    总结:

    上述程序不但在语句行上缩减了两行,更重要的是通过代码优化而提高了效率

    提高程序运行的效率,在编程阶段主要有三个途径:

    (1)吃透问题,采用合理的方案设计;

    (2)采用尽可能有效的算法;

    (3)采用合理的程序结构、内存布局和代码优化。

    上述三者是相辅相成的,你中有我,我中有你。吃透了问题实质,才能合理选择算法;采用更有效的算法,才能实现代码优化;代码优化本身,又是对问题的确切把握。

     

  • 相关阅读:
    Ubuntu下基于Virtualenv构建Python开发环境
    Linux查看用户登录信息-last
    SpringCloud实践引入注册中心+配置中心
    git仓库构建小记
    windows下使用hbase/opencv/ffmpeg小记
    Java执行jar总结
    命名空间
    phpstudy ——composer使用
    template-web.js
    redis
  • 原文地址:https://www.cnblogs.com/ariel-dreamland/p/9091977.html
Copyright © 2020-2023  润新知