我有一个大组字符串,我想为它创建一个自动提示功能.
假设该集合是 ["foo", "fighter"]
键入"f"应该返回两个值,键入"fo"应该只返回"foo".
目前我只是通过调用迭代设置和归档结果startsWith,但是它太慢了.
TreeSet具有子集功能的标准在这里没有多大帮助,因为它只实现了RB树.
Java API中是否存在有效的解决方案,还是必须构建自己的Set实现?
编辑:我的实现看起来像这样,使用Andrey Naumenkos trie数据结构.如果要使用扩展ASCII字符,请注意增加数组大小.如果您使用的是List代替,Map则按排序顺序获得结果.
public Set<String> getSubset(String s) {
result = new HashSet<String>();
getSubset(root, s);
return result;
}
private void getSubset(TrieNode node, String s) {
TrieNode n = node;
for (char ch : s.toCharArray()) {
if (n.children[ch] != null) {
n = n.children[ch];
continue;
}
return;
}
getSubsetR(n, s);
}
private void getSubsetR(TrieNode node, …Run Code Online (Sandbox Code Playgroud) 我在使用 Tokio 时偶然发现了一个死锁情况:
use tokio::time::{delay_for, Duration};
use std::sync::Mutex;
#[tokio::main]
async fn main() {
let mtx = Mutex::new(0);
tokio::join!(work(&mtx), work(&mtx));
println!("{}", *mtx.lock().unwrap());
}
async fn work(mtx: &Mutex<i32>) {
println!("lock");
{
let mut v = mtx.lock().unwrap();
println!("locked");
// slow redis network request
delay_for(Duration::from_millis(100)).await;
*v += 1;
}
println!("unlock")
}
Run Code Online (Sandbox Code Playgroud)
产生以下输出,然后永远挂起。
lock
locked
lock
Run Code Online (Sandbox Code Playgroud)
根据Tokio docs,使用std::sync::Mutex是可以的:
与普遍的看法相反,在异步代码中使用标准库中的普通互斥体是可以的,而且通常是首选。
但是,用Mutexa替换tokio::sync::Mutex不会触发死锁,并且一切都“按预期”工作,但仅限于上面列出的示例情况。在现实场景中,如果延迟是由某些 Redis 请求引起的,它仍然会失败。
我认为这可能是因为我实际上根本没有生成线程,因此,即使“并行”执行,我也会锁定同一个线程,因为等待只是产生执行。
在不产生单独线程的情况下实现我想要的目标的 Rustacean 方法是什么?
algorithm ×1
asynchronous ×1
dictionary ×1
java ×1
mutex ×1
rust ×1
rust-tokio ×1
subset ×1
substring ×1