You can check all 25 Strings interview questions here 👉 https://devinterview.io/data/strings-interview-questions
A string is generally considered as a data type and is often implemented as an array data structure of bytes (or words) that stores a sequence of elements, typically characters, using some character encoding. String may also denote more general arrays or other sequence (or list) data types and structures.
Char arrays:
- Static-sized
- Fast access
- Few built-in methods to manipulate strings
- A char array doesn’t define a data type
Strings:
- Slower access
- Define a data type
- Dynamic allocation
- More built-in functions to support string manipulations
A "string" is really just an array of char
s; a null-terminated string is one where a null character '\0'
marks the end of the string (not necessarily the end of the array). All strings in code (delimited by double quotes ""
) are automatically null-terminated by the compiler.
So for example, "hi"
is the same as {'h', 'i', '\0'}
.
Null-terminated strings are often a drain on performance, for the obvious reason that the time taken to discover the length depends on the length. The usual solution is to do both - keep the length and maintain the null terminator. It's not much extra work and means that you are always ready to pass the string to any function.
Strings can either be mutable or immutable.
- When a string is immutable it means that it's fixed allocated. So your string it's unique and can't be modified. If you change it, a copy of that string is created and the original string is deallocated instead.
- When a string is mutable it means that it's dynamically allocated, so your string can be modified.
The followings are the steps to reversing a String using Stack:
String
tochar[]
.- Create a
Stack
. - Push all characters, one by one.
- Then Pop all characters, one by one and put into the
char[]
. - Finally, convert to the
String
.
Time: O(n)
Space: O(n)
public static String reverse(String str) {
char[] charArr = str.toCharArray();
int size = charArr.length;
Stack stack = new Stack(size);
int i;
for (i = 0; i < size; ++i) {
stack.push(charArr[i]);
}
for (i = 0; i < size; ++i) {
charArr[i] = stack.pop();
}
return String.valueOf(charArr);
}
Thanks 🙌 for reading and good luck on your next tech interview!
Explore 3800+ dev interview question here 👉 Devinterview.io