lintCode 第一题,两个词是否是变位词

问题描述:写出一个函数 anagram(s, t) 去判断两个字符串是否是颠倒字母顺序构成的

变位词,我的理解就是两个单词都含有m种字符,并且每个字符的个数都相同,我的思路是维护一个字符数组,初始化各项为0,首先统计单词W1的各个字符出现的次数。然后对于单词W2,在字符数组中减去各个字符出现的次数,最后,如果字符数组中存在不为0的项,两个词就不是变位词,否则是变位词,假设两个单词的平均长度为m,那么时间复杂度为o(m)。不过需要额外的26个int空间。代码如下:

</pre><pre name="code" class="cpp">#include <stdio.h>
#include <string>
#include <iostream>
#include <algorithm>
#include <windows.h>
using namespace std;


class Solution {
public:
    /**
     * @param s: The first string
     * @param b: The second string
     * @return true or false
     */
    bool anagram(string s, string t) {
        // write your code here
        int sLen = s.size();
        int tLen = t.size();
        if (sLen != tLen)
        {
            return false;
        }
        transform(s.begin(), s.end(), s.begin(), ::tolower);
        transform(t.begin(), t.end(), t.begin(), ::tolower);
        int letterStr[26] = {0};
        for (int i = 0; i < sLen; i++)
        {
            if (s.at(i) == ' ')
            {
                continue;
            }
            if (s.at(i) < 'a' || s.at(i) > 'z')
            {
                return false;
            }
            letterStr[s.at(i) - 'a']++;
        }
        for (int j = 0; j < tLen; j++)
        {
            if (t.at(j) == ' ')
            {
                continue;
            }
            if (t.at(j) < 'a' || t.at(j) > 'z')
            {
                return false;
            }
            letterStr[t.at(j) - 'a']--;
        }
        for (int k = 0; k < 26; k++)
        {
            if (letterStr[k])
            {
                return false;
            }
        }
		return true;
    }
};


int main(void)
{
	Solution solution;
	cout <<solution.anagram("ab", "ab")<<endl;
	system("pause");
	return 0;
}

当然,我觉得这个题目也可以首先对两个字符串进行快速排序,然后比较两个字符串,如果相同,说明是变位词,否则不是,时间复杂度为m*o(log(m)),效率稍微差点。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值