首页 > 解决方案 > C#如何找到字符串中的最后一个唯一字母,并获取它的索引?

问题描述

以下是我要解决的方法.....

public int IndexOfLastUniqueLetter(string str)

我还没有尝试过任何代码,因为我不知道如何解决它。

请告知如何解决此方法以及执行此操作的代码。谢谢,麻烦您了。

标签: c#

解决方案


The algorithm boils down to these two steps:

  • Find which letters are unique,
  • Find the last of these unique letters in the original string.

Counting occurrences of each letter could be done with a loop, or with an associative container, depending on your preferences. If count is 1, the letter is unique; otherwise, it is not unique. Finding last-of could be done by walking the string backward.

The only thing to worry about here is what to do when there are no unique letters in the string (e.g. "aaaa" or "abab"). Your code should detect this condition explicitly, and return -1.


推荐阅读