【两次过】Lintcode 671. 循环单词

本文介绍了一种算法,用于统计给定单词集合中不同循环单词的数量。通过实例解释了如何识别循环单词,并提供了两种解决方案,包括降低空间复杂度的优化方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果一个单词通过循环右移获得的单词,我们称这些单词都为一种循环单词。 现在给出一个单词集合,需要统计这个集合中有多少种不同的循环单词。

例如:picture 和 turepic 就是属于同一种循环单词。

样例

样例 1:

输入 : dict = ["picture", "turepic", "icturep", "word", "ordw", "lint"]
输出 : 3
说明 : 
"picture", "turepic", "icturep" 是相同的旋转单词。
"word", "ordw" 也相同。
"lint" 是第三个不同于前两个的单词。

注意事项

所有单词均为小写。


解题思路1:

一开始的想法是把所有可能的翻转字符全部存入Set中,然后再遍历dict,如果set中不存在则结果加一,最后输出结果即可。但是这样空间复杂度太高了。

public class Solution {
    /*
     * @param words: A list of words
     * @return: Return how many different rotate words
     */
    public int countRotateWords(List<String> words) {
        // Write your code here
        if(words == null || words.size() == 0)
            return 0;
        
        HashSet<String> set = new HashSet<>();
        int res = 0;
        
        for(String word : words){
            if(!set.contains(word)){
                set.addAll(totalRotateWords(word));
                res++;
            }
        }
        
        return res;
    }
    
    //输出word所有可能的翻转字符
    private List<String> totalRotateWords(String word){
        List<String> res = new ArrayList<>();
        
        for(int i=0; i<word.length(); i++){
            res.add(rotateWord(word,i));
        }
        
        return res;
    }
    
    //根据n位置,翻转word
    private String rotateWord(String word, int n){
        StringBuilder s = new StringBuilder(word);
        StringBuilder ss = s.reverse();
        StringBuilder temp1 = new StringBuilder(ss.substring(0,n+1));
        StringBuilder ssL = temp1.reverse();
        StringBuilder temp2 = new StringBuilder(ss.substring(n+1));
        StringBuilder ssR = temp2.reverse();
        
        StringBuilder res = new StringBuilder();
        res.append(ssL);
        res.append(ssR);
        
        return res.toString();
    }
}

二刷

public class Solution {
    /*
     * @param words: A list of words
     * @return: Return how many different rotate words
     */
    public int countRotateWords(List<String> words) {
        // Write your code here
        Set<String> set = new HashSet<>();
        int res = 0;
        
        for(String str : words){
            if(!set.contains(str)){
                res++;
                
                String s = str + str;
                for(int i=0; i<str.length(); i++)
                    set.add(s.substring(i, i+str.length()));
            }
        }
        
        return res;
    }
}

解题思路2:

为了降低空间复杂度,建立set后边添加边移除,思路是遍历words,对于每一个word先在set中删除所有关于此word的所有翻转字符,然后再添加一个,这样如果遍历到相同字符得来的翻转字符则总会只添加一个。

其中求word所有的翻转字符,有一个简单的方法:可以先将w变成w+w,然后求新字符串的substring。这样不需要考虑前后拼接问题,代码更简练。

public class Solution {
    /*
     * @param words: A list of words
     * @return: Return how many different rotate words
     */
    public int countRotateWords(List<String> words) {
        // Write your code here
        Set<String> set = new HashSet<String>();

        for (String w : words) {
            String s = w + w;
            //移除set中关于w所有的翻转字符
            for (int i = 0; i < w.length(); i++) 
                set.remove(s.substring(i, i + w.length()));

            set.add(w);
        }

        return set.size();
    }

}

 

### LintCode 1369 最频繁单词 解法 LintCode 平台上编号为 1369 的题目涉及统计最频繁出现的单词。以下是对此类问题的一种通用解法。 #### 方法概述 此问题可以通过哈希表来解决,其中键表示不同的单词,而值则记录每个单词出现的次数。通过遍历输入数据并更新哈希表中的计数值,最终找到频率最高的单词及其对应的频次。 #### 实现细节 为了实现这一目标,可以按照以下逻辑编写代码: 1. **预处理**: 清理输入字符串,移除标点符号并将所有字母转换成小写形式以便统一比较标准。 2. **构建词频映射**: 使用 Python 中的 `collections.Counter` 或手动维护一个字典结构存储各单词与其对应出现次数之间的关系。 3. **查找最大值**: 遍历上述得到的词频映射找出具有最高频率的那个单词或者多个相同频率的最大者之一即可满足需求。 下面是基于以上思路的具体实现代码: ```python from collections import Counter import re def topKFrequentWords(words, k): # 正则表达式替换非字母字符为空格,并分割成列表 cleaned_words = re.sub(r'[^a-zA-Z]', ' ', words).lower().split() # 统计词频 count = Counter(cleaned_words) # 获取按频率降序排列的结果 candidates = list(count.items()) candidates.sort(key=lambda w: (-w[1], w[0])) # 返回前K个高频单词 return [word for word, freq in candidates[:k]] # 测试样例 words = "the sky is blue and the color of the sea is also blue" print(topKFrequentWords(words, 2)) # 输出可能为 ['blue', 'the'] ``` 在此段代码中我们利用了正则表达式的功能去除了不必要的特殊字符,并且采用了大小写的标准化操作使得不同格式下的同一词语能够被正确识别为同一个实体。最后借助于Python内置库`Counter`完成了高效地词频计算工作[^1]。 #### 注意事项 - 当存在若干个拥有相同比率的候选答案时,应优先选取字典顺序靠前者作为最终结果的一部分条件。 - 输入验证非常重要,在实际应用环境中应当加入更多异常情况检测机制以增强程序健壮性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值