When to initialize an array with 256

I was looking through cracked solutions for interview books and noticed the following problem:

Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?

This was one of the solutions:

public static boolean isUniqueChars2(String str) { boolean[] char_set = new boolean[256]; for (int i = 0; i < str.length(); i++) { int val = str.charAt(i); if (char_set[val]) return false; char_set[val] = true; } return true; } 

Why is the char_set array initialized to 256? I thought this was because there are 128 ascii characters, but I'm not sure. Also, this solution is similar to Java, but should there be an initial size if it was done in C ++?

+5
source share
3 answers

I thought this was because there are 128 ascii characters, but I'm not sure.

No. With extended ASCII codes, there are only 256 characters. This is the reason for 256.

http://www.asciitable.com/

In addition to the reason given for 256 , note that com /

Please note that, as Erwin Bolvidt said, the code is incomplete at best anyway, because Java characters are not ASCII or extended ASCII. They are the “16-bit Unicode character”, so the array must be a new boolean [65536]

+6
source

The extended ASCII char set has 2 ^ 8 = 256 characters.

Check it out here. http://www.ascii-code.com/

The solution tells you about 1 and 0 can only be two values. That's why it uses a primitive array of values ​​from a boolean. Without initialization, a logical variable is always FALSE.

C ++ allows

 bool arr[256] = {}; 

good example for arrays:

 #include <iostream> using namespace std; int main() { bool test1[16] = { false }; bool test2[16] = { true }; bool test3[16]; cout << "Test1 - Init to false" << endl; for (size_t i = 0; i < sizeof(test1)/sizeof(test1[0]); ++i) cout << test1[i]; cout << endl << "Test2 - Init to true" << endl; for (size_t i = 0; i < sizeof(test2)/sizeof(test2[0]); ++i) cout << test2[i]; cout << endl << "Test3 - Uninitialized" << endl; for (size_t i = 0; i < sizeof(test3)/sizeof(test3[0]); ++i) cout << test3[i]; cout << endl; } 

and gives results like:

 Test1 - Init to false 0000000000000000 Test2 - Init to true 1000000000000000 Test3 - Uninitialized 12024619195255127009671929525512700 
+1
source

Btw code is in Java.

 boolean[] char_set = new boolean[256] 

will be

 bool* char_set = new bool[256] 

in c ++

+1
source

Source: https://habr.com/ru/post/1232666/


All Articles