正如 Andy Turner 的 correct Answer 所说,使用 Set 跟踪单个对象,而不是使用 Map 跟踪对象对。
代码点
char 类型(及其包装类Character)是遗留的,并且基本上已损坏。作为一个 16 位的值,它不能代表大多数字符。
改为使用code point 整数。
public static String firstRecurringCharacter ( List < String > inputs )
{
Objects.requireNonNull( inputs );
Set < Integer > seen = new HashSet <>();
for ( String s : inputs )
{
Objects.requireNonNull( s , "Input of list of String objects contained a null." );
if ( s.length() != 1) throw new IllegalStateException( "Input of list of String objects contained an element with other than one character." );
if ( ! seen.add( s.codePointAt( 0 ) ) )
{
return s;
}
}
return null;
}
用法。
List < String > inputX = List.of( "D" , "B" , "C" , "A" , "B" , "A" );
List < String > inputY = List.of( "D" , "B" , "C" , "A" , "E" , "T" );
System.out.println( App5.firstRecurringCharacter( inputX ) );
System.out.println( App5.firstRecurringCharacter( inputY ) );
运行时。
B
空
Optional
将 null 作为合法值返回是有问题的。在这种情况下,请使用 Optional 包装器。
public static Optional < String > firstRecurringCharacter ( List < String > inputs )
{
Objects.requireNonNull( inputs );
Set < Integer > seen = new HashSet <>();
for ( String s : inputs )
{
Objects.requireNonNull( s , "Input of list of String objects contained a null." );
if ( s.length() != 1 ) throw new IllegalStateException( "Input of list of String objects contained an element with other than one character." );
if ( ! seen.add( s.codePointAt( 0 ) ) )
{
return Optional.of( s );
}
}
return Optional.empty();
}
用法。
List < String > inputX = List.of( "D" , "B" , "C" , "A" , "B" , "A" );
List < String > inputY = List.of( "D" , "B" , "C" , "A" , "E" , "T" );
System.out.println( App5.firstRecurringCharacter( inputX ).orElse( "No recurring characters." ) );
System.out.println( App5.firstRecurringCharacter( inputY ).orElse( "No recurring characters." ) );
运行时。
B
没有重复的字符。
String 而不是字符列表
当然,在上面的代码中,你不需要使用代码点整数给定一个字符串输入,每个字符串都有一个字符。您可以只为代码点创建 Set< String > 而不是 Set< Integer >。
代码点的用处在于拆分一个由多个字符组成的字符串。所以调用程序员不需要传递单字符串的集合。相反,可以传递多个字符的String。
public static Optional < String > firstRecurringCharacter ( String input )
{
Objects.requireNonNull( input );
int[] codePoints = input.codePoints().toArray();
Set < Integer > seen = new HashSet <>();
for ( int codePoint : codePoints )
{
if ( ! seen.add( codePoint ) )
{
return Optional.of( Character.toString( codePoint ) );
}
}
return Optional.empty();
}
用法。
String inputX = "DBCABA";
String inputY = "DBCAET";
String inputZ = "?ABC?ABC";
System.out.println( App5.firstRecurringCharacter( inputX ).orElse( "No recurring characters." ) );
System.out.println( App5.firstRecurringCharacter( inputY ).orElse( "No recurring characters." ) );
System.out.println( App5.firstRecurringCharacter( inputZ ).orElse( "No recurring characters." ) );
运行时。
B
没有重复的字符。
?