lintcode 不允许成对

lintcode 不允许成对

描述

你有一家专门经营没有相邻匹配字符的单词的精品店。鲍比,一个竞争对手,已经决定完全退出这个业务并且你买了他的库存,你的想法是修改他的词汇库存,使他们适合在你的商店出售。为此,你找到所有相邻的匹配字符对,并将其中一个字符替换为另一个字符对。确定必须替换的最小字符数,以生成一个畅销词。例如,你购买了 words = [“odd”,“boook”,“treak”]。在 “add” 中更改 ‘d’,在 “boook” 中更改 ‘o’,在 “break” 中不需要更改。返回数组 result = [1,1,0]。

在下面的编辑器中完成函数的最小操作。函数必须返回一个整数数组,每个 result[i] 是修复 words[i] 所需的最小操作。

1 <= n <= 100
2 <= len(words[i]) <= 10^5
words[i] 为 ascii[‘a’-‘z’]

样例

样例 1:

输入:[“ab”,“aab”,“abb”,“abab”,“abaaaba”]
输出:[0,1,1,0,1]
样例 2:

输入:[“odd”,“boook”,“treak”]
输出:[1,1,0]

思路

找到每个字符串中相邻重复元素的长度,需要改变的个数是(int)长度/2

代码

class Solution {
public:
    /**
     * @param words: The array words that you need to calculate minimal operation .
     * @return: Return an array of integers, each result[i] being the minimum operations needed to fix words[i].
     */
    vector<int> minimalOperation (vector<string> &words) {
        // Write your code here.
        vector<int> res(words.size(), 0);
        for (int i = 0; i < words.size(); i++) {
            string temp = words[i];
            for (int j = 0; j < temp.length()-1;) {
                int k = 0;
                while (temp[j] == temp[j+k])
                    k++;
                res[i] += k/2;
                j += k;
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_40147449/article/details/88893857