​LeetCode解法汇总2451. 差值数组不同的字符串

目录链接:

力扣编程题-解法汇总_分享+记录-CSDN博客

GitHub同步刷题项目:

https://github.com/September26/java-algorithms

原题链接:力扣


描述:

给你一个字符串数组 words ,每一个字符串长度都相同,令所有字符串的长度都为 n 。

每个字符串 words[i] 可以被转化为一个长度为 n - 1 的 差值整数数组 difference[i] ,其中对于 0 <= j <= n - 2 有 difference[i][j] = words[i][j+1] - words[i][j] 。注意两个字母的差值定义为它们在字母表中 位置 之差,也就是说 'a' 的位置是 0 ,'b' 的位置是 1 ,'z' 的位置是 25 。

  • 比方说,字符串 "acb" 的差值整数数组是 [2 - 0, 1 - 2] = [2, -1] 。

words 中所有字符串 除了一个字符串以外 ,其他字符串的差值整数数组都相同。你需要找到那个不同的字符串。

请你返回 words中 差值整数数组 不同的字符串。

示例 1:

输入:words = ["adc","wzy","abc"]
输出:"abc"
解释:
- "adc" 的差值整数数组是 [3 - 0, 2 - 3] = [3, -1] 。
- "wzy" 的差值整数数组是 [25 - 22, 24 - 25]= [3, -1] 。
- "abc" 的差值整数数组是 [1 - 0, 2 - 1] = [1, 1] 。
不同的数组是 [1, 1],所以返回对应的字符串,"abc"。

示例 2:

输入:words = ["aaa","bob","ccc","ddd"]
输出:"bob"
解释:除了 "bob" 的差值整数数组是 [13, -13] 以外,其他字符串的差值整数数组都是 [0, 0] 。

提示:

  • 3 <= words.length <= 100
  • n == words[i].length
  • 2 <= n <= 20
  • words[i] 只含有小写英文字母。

解题思路:

* 解题思路:
* 也许我想复杂了,所以想了一个相对复杂一点的方案。
* 遍历words,每个word都生成一个唯一的key字符串,格式为1_11_这样,其中1和11代表差值。
* 然后添加到map中,其中key为上面生成的,value就代表次数。
* 那么value=1的就是我们要找的那个字符。

代码:

#include <iostream>
#include <map>
#include <list>
#include <vector>
#include <map>
#include "Solution2451.h"

/**
 * 思路:
 */
string Solution2451::oddString(vector<string> &words)
{

    const char *chars = words[0].data();
    map<string, int> wordMap;
    map<string, string> wordMap2;
    for (int i = 0; i < words.size(); i++)
    {
        string builder;
        const char *chars = words[i].data();
        // for (int j = 1; j < sizeof(chars); j++)
        for (int j = 1; j < words[i].size(); j++)
        {
            builder.append(to_string((chars[j] - 'a') - (chars[j - 1] - 'a')));
            builder.append("_");
        }
        wordMap[builder] = wordMap[builder] + 1;
        wordMap2[builder] = words[i];
    }
    map<string, int>::iterator it;
    for (it = wordMap.begin(); it != wordMap.end(); it++)
    {
        if (it->second == 1)
        {
            return wordMap2[it->first];
        }
    }

    return "";
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

失落夏天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值