gpt4 book ai didi

java - 实现一种算法来确定字符串是否具有所有唯一字符(大于 U+FFFF 的字符)

转载 作者:行者123 更新时间:2023-11-30 08:37:53 26 4
gpt4 key购买 nike

我正在练习示例面试问题,其中之一是:“实现一种算法以确定字符串是否具有所有唯一字符”。

当我们假设是 ASCII/ANSI 时,这很容易。 implement-an-algorithm-to-determine-if-a-string-has-all-unique-charact

但我的问题是:如果假设字符串可以包含例如象形文字符号或其他任何符号(代码点大于 U+FFFF...?)。

因此,如果我理解正确的话,如果给定的字符串包含属于从 U+0000 到 U+FFFF 的字符集的字符,我可以很容易地想到解决方案——它们可以转换为 16 位字符,但是如果我遇到代码点大于 U+FFFF... 的字符?

Characters whose code points are greater than U+FFFF are called supplementary characters. The Java platform uses the UTF-16 representation in char arrays and in the String and StringBuffer classes. In this representation, supplementary characters are represented as a pair of char values, the first from the high-surrogates range, (\uD800-\uDBFF), the second from the low-surrogates range (\uDC00-\uDFFF)

但我不知道在那种情况下如何解决这个难题,我该如何处理这些代理对?

谢谢!

最佳答案

Java 8 有一个 CharSequence#codePoints method生成字符串中 Unicode 代码点的 IntStream。从那里开始,只需编写代码来测试 IntStream 中元素的唯一性即可。

如果您仍在使用 Java 7 或更低版本,那里有基于代码点的方法也可用于解决此问题,但它们使用起来要复杂得多。您必须遍历字符串的 char 并检查每个值以判断您是否正在处理代理项对。类似的东西(完全未经测试):

for (int i = 0; i < str.length(); i++) {
int codepoint = str.codePointAt(i++);
if (Character.isHighSurrogate(str.charAt(i))) {
// This will fail if the UTF-16 representation of
// this string is wrong (e.g., high surrogate `char`
// at the end of the string's `char[]`).
i += 1;
}
// do stuff with codepoint...
}

关于java - 实现一种算法来确定字符串是否具有所有唯一字符(大于 U+FFFF 的字符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36871838/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com