英文:
Question in regards to a line of the code
问题
在下面的代码片段中,我有一个问题,给定的声明数组的类型是整数。你能解释一下在map[s.charAt(i)]++
这一行发生了什么吗?我在理解这个语句时遇到了困难,因为在初始化期间数组的类型是整数,但输入却是字符类型。
public int firstUniqChar(String s)
{
int[] map = new int[128];
for(int i=0; i<s.length(); i++)
map[s.charAt(i)]++;
for(int i=0; i<s.length(); i++)
if(map[s.charAt(i)] == 1)
return i;
return -1;
}
英文:
In the below code snipped I have a question, the given declared array is of type integer.Can you please explain on what is happening at the line map[s.charAt(i)]++. I am having trouble understanding the statement here as the array is of type integer during initialization, but character type are being given as input.
public int firstUniqChar(String s)
{
int[] map = new int[128];
for(int i=0;i<s.length();i++)
map[s.charAt(i)]++;
for(int i=0;i<s.length();i++)
if(map[s.charAt(i)] == 1)
return i;
return -1;
}
答案1
得分: 1
在Java中,假设您有一个int i = 0
的变量声明,i++
是一个语法糖,用于将1添加到变量值,即i = i + 1
。
在您的情况下,您正在将1添加到由s.charAt(i)
索引的map
数组位置。
假设s
是一个String对象,s.charAt(i)
返回位置为i
(从0开始计数)的char
。当Java将char
读取为int
(用于索引map
数组)时,它使用该char
的ASCII码。
因此,map[s.charAt(i)]++
的作用是将1添加到由字符的ASCII码索引的map
数组。
英文:
In java, supposing you have a int i = 0
variable declaration, the i++
is a syntax suggar to sum 1 to variable value, i.e. i = i + 1
.
In your case you are summing 1 to an map
array position, indexed by s.charAt(i)
.
Supposing s
is a String object, s.charAt(i)
returns the char
at the i
position (0-indexed). When the Java reads the char
as a int
(to index the map
array), is uses the ASCII code of that char
.
So, what map[s.charAt(i)]++
does is to sum 1 to the map
array indexed by the charactere's ASCII code.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论