【问题标题】:What is count[str.charAt(i)]++ actually storing? [duplicate]count[str.charAt(i)]++ 实际存储的是什么? [复制]
【发布时间】:2019-06-13 08:03:24
【问题描述】:

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

这个问题其实是我看了解决方案后才解决的。但我不明白 getCharOccur 函数中发生了什么。明确地,count[str.charAt(i)]++ 中究竟存储了什么。该数组中的索引和值是什么。同样在开始时,为什么我们将 count[] 声明为具有 256 个字符的空数组的动态数组?我尝试打印 count[str.charAt(i)]++ 但它在控制台中显示了一些空值。

public class Main {
    static final int chars=256;
    static char count[]=new char[chars];

    //calculating the number of occurences of each character
      static void getCharOccur(String str){
        for(int i=0; i<str.length(); i++){
            count[str.charAt(i)]++;

        }
    }

    //Calculating index of first non repeating character
    static int getNonRepeatChar(String str){
        getCharOccur(str);
        int index=-1;
        for(int i=0; i<str.length(); i++){
            if(count[str.charAt(i)]==1){
                index=i;
                break;
            }
        }
        return index;
    }

public static void main(String[] args) {
        String str="thisisit";
        int index=getNonRepeatChar(str);
        System.out.println(index==-1 ? "Either all characters are 
        "repeating character is  "+str.charAt(index));

    }
}

打印出来的结果是有效的:第一个不重复的字符是 h

【问题讨论】:

  • 你忘记发getCharOccur()的代码了...

标签: java data-structures


【解决方案1】:

char 只是一个无符号整数,代表一个 unicode 字符。

您也可以将它用作一个数字,它从\u0000 开始,如果您增加它,您可以获得\u0001,您也可以像任何数字一样对其进行数学运算。

这是一个示例,我附上了解释它的视频。

https://twitter.com/PeterLawrey/status/1131620691906891777

注意:char 在 65535 之后溢出,因此不是一个好的选择,除了它令人困惑之外。使用int[] 会是更好的选择。

【讨论】:

    猜你喜欢
    • 2019-05-03
    • 2014-05-09
    • 2019-11-15
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 2021-09-17
    • 1970-01-01
    相关资源
    最近更新 更多