您好,欢迎访问一九零五行业门户网

如何在Java中找出第一个不重复的字符?

如何从字符串中找出第一个不重复的字符?
比如说字符串“沉默王沉沉默二”,第一个不重复的字符是“王”,对吧?因为“沉”重复了,“默”重复了。
public class findnonrepeatingchar {     public static void main(string[] args) {         system.out.println(printfirstnonrepeatingchar(沉默王沉沉默二));         system.out.println(printfirstnonrepeatingchar(沉默王沉));         system.out.println(printfirstnonrepeatingchar(沉沉沉));     }      private static character printfirstnonrepeatingchar(string string) {         char[] chars = string.tochararray();          list<character> discardedchars = new arraylist<>();          for (int i = 0; i < chars.length; i++) {             char c = chars[i];              if (discardedchars.contains(c))                 continue;              for (int j = i + 1; j < chars.length; j++) {                 if (c == chars[j]) {                     discardedchars.add(c);                     break;                 } else if (j == chars.length - 1) {                     return c;                 }             }         }         return null;     } }
输出结果如下所示:
王 默 null
说一下我的思路:
1)把字符串拆分成字符数组。
2)声明一个 list,把重复的字符放进去。
3)外层的 for 循环,从第一个字符开始,如果已经在 list 中,继续下一轮。
4)嵌套的 for 循环,从第一个字符的下一个字符(j = i + 1)开始遍历,如果找到和之前字符重复的,就加入到 list  中,跳出内层的循环;如果找到最后(j == chars.length - 1)也没有找到,就是第一个不重复的字符,对吧?
以上就是如何在java中找出第一个不重复的字符?的详细内容。
其它类似信息

推荐信息