使用LinkedHashMap的字符串中的第一个唯一字符 [英] First unique character in a string using LinkedHashMap

查看:95
本文介绍了使用LinkedHashMap的字符串中的第一个唯一字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个字符串,找到其中的第一个非重复字符并返回其索引.如果不存在,则返回 -1 .

Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.

示例:

s = "leetcode"
return 0.

s = "loveleetcode"
return 2.

在我的解决方案中,我可以找到角色本身,但我正在寻找角色的索引!如何使用 LinkedHashMap 更改代码以获取索引?并先谢谢您.

In my solution I can find the character itself but I am looking to get the index of the character! How would I change my code to get the index using LinkedHashMap? And thank you in advance.

public static void firstNonRepeatingString(String str) {
    LinkedHashMap<Character, Integer> lhm = new LinkedHashMap<>();
    char[] charArray = str.toCharArray();
    for (char character : charArray) {
        if (lhm.get(character) == null) {
            lhm.put(character, 1);
        } else {
            lhm.put(character, lhm.get(character) + 1);
        }
    }

    for (Map.Entry<Character, Integer> entry : lhm.entrySet())
        if (entry.getValue() == 1) {
            System.out.print(entry.getKey());
            break;
        }
}

firstNonRepeatingString("aaabcccddeggf"); 

这将打印 b ,但是我想打印 3 .

This will print b, but I want to print 3.

推荐答案

HashSet

该集合仅用于避免再次计算已经看到的字符.该集不需要遵循插入顺序,因为它的目标只是检查元素是否存在.为此, HashSet 是一个适当的选项.

HashSet

The set is only used to avoid computing again a character that's already been seen. The set doesn't need to respect insertion order, as its goal is just check if an element exists. For that, HashSet is a proper option.

StringUtils 确实具有一些很好的实用程序,其中之一是统计源字符串中单个字符/字符串的出现次数.

StringUtils has some good utils indeed, one of them is counting the occurrences of a single char/string within the source string.

由于您想要第一个唯一的字符,如果 set 中不存在该元素,并且 countMatches 返回 1 ,则您得到了你的结果.

As you want the first character which is unique, if the element didn't exist in the set and countMatches returns 1, you got your result.

如果未找到唯一性,请返回 -1 (例如)作为表示在字符串中未找到唯一性的表示.

If no uniques are found, return -1 (for example) as representation that no uniques were found in the string.

public static int firstNonRepeatingCharIndex(String str) 
{
   HashSet<Character> dupSet = new HashSet<>();   //duplicates list
   for(char c : str.toCharArray()) 
   {
      if (dupSet.contains(c))
          continue;
      if (StringUtils.countMatches(str, c) == 1)
          return str.indexOf(c);
      dupSet.add(c);
   }
   return -1;
}

这可以避免:

  • 找到结果后,所有字符都无用的迭代.
  • 已经看到无用的字符处理了.
  • 无用的地图创建及其相关操作,例如聚合.

对于此特定问题,这不是必需的,但以防万一您想知道哪些是唯一性及其顺序,因此您想使用两个 Sets 进行迭代直到最后可能是一个选择.

For this specific problem, this shouldn't be required, but just in case you want to know which are the uniques and their order, so you want to iterate until the end, using two Sets could be an option.

public static int firstNonRepeatingCharIndex(String str) 
{
   LinkedHashSet<Character> lSet = new LinkedHashSet<>();
   HashSet<Character> dupSet = new HashSet<>();   //duplicates list

   for(char character : str.toCharArray()) 
   {
      if (dupSet.contains(character))  //exists in duplicates, continue
          continue;         
      if (lSet.contains(character))   //exists in the linkedSet, add to duplicates
          dupSet.add(character);          
      else
          lSet.add(character);        //first time seen, add to linkedSet
   } 

   lSet.removeAll(dupSet);          //remove all duplicates 
   if (lSet.isEmpty())
        return -1;

   return str.indexOf(lSet.iterator().next());  
}


LinkedHashMap

仅当需要完整的地图,获取统计信息或其他任何内容时.

请注意,无需添加/修改条目.如果密钥不在地图中,我们将直接设置出现次数.

Note there's no need to add/modify the entries. We directly set the number of occurrences if the key is not in the map.

public static int firstNonRepeatingCharIndex(String str) 
{
  LinkedHashMap <Character , Integer> lhm = new LinkedHashMap<>();
  int c = 0, index = -1;
  for(char character : str.toCharArray()) 
  {
     if (lhm.get(character) == null)
     {
        int oc = StringUtils.countMatches(str,character);
        if (oc==1 && index<0)
           index = c;           //will only bet set once
        lhm.put(character, oc);
      }            
      if (index<0)     
        c++;                   //no need for this after index is found
   } 
   //showStatsOfMap(lhm); ?
   return index;
}


如果您根本不需要地图的结果(这使您想知道为什么这里有地图)

public static int firstNonRepeatingCharIndex(String str) 
{
   LinkedHashMap <Character , Integer> lhm = new LinkedHashMap<>();
   int c = 0;
   for(char character : str.toCharArray()) 
   {
      if (lhm.get(character)==null)
      {
          int oc = StringUtils.countMatches(str,character);
          if (oc == 1)
             return c;
          lhm.put(character, oc);
      }
       c++;
   }    
    //sendNonUniqueMap(lhm); //??? just to make use of it...
    return -1;
 }

这篇关于使用LinkedHashMap的字符串中的第一个唯一字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆