博客
关于我
Leetcode 面试经典 01.02 判定是否互为字符重排(C/C++)
阅读量:607 次
发布时间:2019-03-11

本文共 1334 字,大约阅读时间需要 4 分钟。

大家好,我是小黄,今天遇到了一个编程题,任务是判断两个字符串是否可以通过重新排列字符变成对方。这个问题看起来不难,但为了确保正确,还是需要仔细分析一下解决方案。

问题分析

给定两个字符串s1和s2,判断是否一个字符串的字符重新排列后可以变成另一个字符串。这是一个常见的 Sorting(排序)问题,可以利用字符频率进行比较判定。

解决方法

为了判断两个字符串是否可以重新排列成对方,关键在于比较两个字符串的字符频率是否相同。可以采用以下两种方法进行解决:

  • 排序后比较:将两个字符串分别排序,然后比较排序后的结果是否相同。如果相同,则可以重新排列,否则不能。

  • 数组转换法:创建一个大小为256的数组(涵盖ASCII码),记录两个字符串中每个字符的出现次数。对于第一个字符串,统计每个字符的出现次数并增加对应位置的计数;对于第二个字符串,减少相应位置的计数。最后,检查数组中是否存在非零值。如果有,说明字符频率不同,返回false。

  • 优化思考

  • 判断长度:首先检查两个字符串的长度是否相同。如果长度不同,直接返回false,避免后续处理。

  • 选择排序或计数方法:两种方法各有优劣。排序方法简单易懂,适合处理较短的字符串。而计数方法在处理较长字符串时可能效率更高,因为只需两次遍历字符串。

  • 代码实现

    以下是使用排序方法的实现:

    #include 
    #include
    using namespace std;bool CheckPermutation(string s1, string s2) { if (s1.size() != s2.size()) return false; sort(s1.begin(), s1.end()); sort(s2.begin(), s2.end()); return s1 == s2;}

    另一种是使用计数数组的方法:

    #include 
    #include
    using namespace std;bool CheckPermutation(string s1, string s2) { if (s1.size() != s2.size()) { return false; } array
    count = {0}; for (char c : s1) { count[c]++; } for (char c : s2) { count[c]--; } for (int i = 0; i < 256; ++i) { if (count[i] != 0) { return false; } } return true;}

    以上代码都可以有效地解决问题,答案通过了测试。

    总结

    问题解决关键在于比较两个字符串的字符频率。无论选择哪种方法,都需要确保字符分布完全一致。通过判断长度和字符频率,可以有效地实现字符串排列判断功能。

    转载地址:http://rzhtz.baihongyu.com/

    你可能感兴趣的文章
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
    查看>>
    NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
    查看>>
    Node JS: < 一> 初识Node JS
    查看>>
    Node-RED中使用JSON数据建立web网站
    查看>>