273. Integer to English Words

本文介绍了一种将非负整数转换为其英文单词表示的方法,适用于小于2^31 - 1的整数。通过使用预定义的数组来处理个位、十位、百位及千位以上的数字,并通过递归地分解数字来实现转换。

问题链接:https://leetcode.com/problems/integer-to-english-words/?tab=Description

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

For example,

123 -> "One Hundred Twenty Three"
12345 -> "Twelve Thousand Three Hundred Forty Five"
1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

Hint:

  1. Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000.
  2. Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words.
  3. There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)

想了半天还是没什么思路,参照答案默写如下:

public class Solution {
    private String TENS[] = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    private String LESS_THAN_TWENTY[] = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    private String THOUSANDS[] = {"", "Thousand", "Million", "Billion"};
    
    public String numberToWords(int num) {
        if(num == 0) return "Zero";
        
        String result = "";
        int i = 0;
        
        while(num > 0) {
            if(num%1000 != 0)
                result = helper(num%1000) + THOUSANDS[i] + " " + result;
            num = num / 1000;
            i++;
        }
        
        return result.trim();
    }
    
    private String helper(int value) {
        if(value == 0)
            return "";
        else if(value < 20) {
            return LESS_THAN_TWENTY[value] + " ";
        } 
        else if(value < 100) {
            return TENS[value/10] + " " + helper(value%10);
        } 
        else {
            return LESS_THAN_TWENTY[value/100] + " Hundred " + helper(value%100);
        }
    }
}


package util; import com.hankcs.hanlp.HanLP; import edu.stanford.nlp.pipeline.*; import edu.stanford.nlp.ling.CoreAnnotations; import edu.stanford.nlp.util.CoreMap; import java.util.*; import java.util.stream.Collectors; import java.io.File; import java.io.FileNotFoundException; public class NlpUtil { private static final Set<String> STOP = loadStop(); private static final Set<String> SUF = Set.of("技术","系统","方法","装置","设备","算法","模型","框架"); // 使用简单的RAKE实现替代外部依赖 private static final SimpleRake RAKE = new SimpleRake(); private static final StanfordCoreNLP NLP; static { Properties p = new Properties(); p.setProperty("annotators", "tokenize,ssplit,pos,lemma,ner"); NLP = new StanfordCoreNLP(p); } private static Set<String> loadStop() { Set<String> set = new HashSet<>(); try (Scanner sc = new Scanner(new File("中文停用词表.txt"), "UTF-8")) { while (sc.hasNext()) set.add(sc.nextLine().trim()); } catch (Exception ignored) {} return set; } public static Result kwEnt(String text) { if (text == null || text.isBlank()) return new Result(List.of(), ""); boolean zh = text.chars().anyMatch(c -> c >= '\u4e00' && c <= '\u9fff'); List<String> kw = zh ? zhKw(text) : enKw(text); String ent = zh ? zhEnt(text) : enEnt(text); return new Result(kw, ent); } private static List<String> zhKw(String t) { return HanLP.extractKeyword(t, 4).stream() .filter(w -> !STOP.contains(w) && w.length() > 1) .collect(Collectors.toList()); } private static String zhEnt(String t) { return HanLP.segment(t).stream() .map(term -> term.word) .filter(w -> SUF.stream().anyMatch(w::endsWith)) .filter(w -> !STOP.contains(w) && w.length() > 1) .distinct() .map(w -> w + "/TECH") .collect(Collectors.joining(",")); } private static List<String> enKw(String t) { return RAKE.extract(t).stream().limit(10).collect(Collectors.toList()); } private static String enEnt(String t) { Annotation an = new Annotation(t); NLP.annotate(an); List<CoreMap> mentions = an.get(CoreAnnotations.MentionsAnnotation.class); if (mentions == null) return ""; return mentions.stream() .map(m -> m.get(CoreAnnotations.TextAnnotation.class) + "/" + m.get(CoreAnnotations.EntityTypeAnnotation.class)) .collect(Collectors.joining(",")); } // 简单的RAKE实现 private static class SimpleRake { private static final Set<String> ENGLISH_STOP_WORDS = Set.of( "a", "an", "the", "and", "or", "but", "in", "on", "at", "to", "for", "of", "with", "by" ); public List<String> extract(String text) { if (text == null || text.isBlank()) return new ArrayList<>(); // 简单的关键词提取逻辑 String[] words = text.toLowerCase().split("\\W+"); Map<String, Integer> wordScores = new HashMap<>(); for (String word : words) { if (word.length() > 2 && !ENGLISH_STOP_WORDS.contains(word)) { wordScores.put(word, wordScores.getOrDefault(word, 0) + 1); } } // 按频率排序 return wordScores.entrySet().stream() .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue())) .map(Map.Entry::getKey) .collect(Collectors.toList()); } } public static class Result { public final List<String> keywords; public final String entities; private Result(List<String> k, String e) { keywords = k; entities = e; } public String entities() { return entities; } } }解释一下代码
最新发布
12-13
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值