CareerCup String getSentence(String text, Set<String> dictionary); O(n)

本文介绍了一种用于将无空格字符串根据字典高效拆分成独立词汇的算法,并提供了一个具体的Java实现示例。该算法利用递归方法遍历字符串的所有可能拆分方式,通过检查子串是否存在于给定的词汇表中来决定是否采用该拆分方案。

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

String getSentence(String text, Set<String> dictionary); 

// text is a string without spaces, you need to insert spaces into text, so each word seperated by the space in the resulting string exists in the dictionary, return the resulting string 

// running time has to be at least as good as O(n) 

 

 

// getSentence("iamastudentfromwaterloo", {"from, "waterloo", "hi", "am", "yes", "i", "a", "student"}) -> "i am a student from waterloo"

 

 

---------------------------------------------------------------

 

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

class Solution {
	
	public static void main(String[] args) {
		
		Solution instance = new Solution();
		Set<String> dictionary = new HashSet();
		dictionary.add("google");
		dictionary.add("is");
		dictionary.add("awesome");
		List<String> store = new ArrayList<String>();
		instance.printWords("googleisawesome", store, dictionary);
		for(int i = store.size() - 1; i >= 0; --i) {
			System.out.println(store.get(i));
		}
	}


	private boolean printWords(String string, List<String> store, Set<String> dictionary) {
		if(string.length() == 0) {
			return true;
		}
		for(int i = 1; i <= string.length(); ++i) {
			String curWord = string.substring(0, i);
			if(dictionary.contains(curWord) && printWords(string.substring(i), store, dictionary)) {
				store.add(curWord);
				return true;
			}
		}
		return false;
	}
}

Trie tree is expected for this problem...

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值