My question is related to "longest common prefix" problem in LeetCode.(https://leetcode.com/problems/longest-common-prefix/)
Here is my code:
#include <string>
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int cnt = 0;
string result = "";
char ch = ' ';
char standard = ' ';
for(int i=0; i<strs.size(); i++){
if(strs[i].size() == 0) return result;
}
if(strs.size() == 1){
return strs[0];
}
while(1){
standard = strs[0][cnt];
for(int i=0; i<strs.size(); i++){
ch = strs[i][cnt];
if(ch == '\0' || ch != standard) return result;
}
result+=ch;
cnt++;
}
}
};
While iterating every single character in vector's string elements, I tried to handle exceptions like all elements in string vectors are totally equal by using code
if(ch == '\0'...)
But I've learned that string class in C++ does not contain null character at the end of the string, so I thought this code wouldn't work as code that I wrote was meaningless.
But why does this code work...?
Does C++ put null character automatically in string vector's elements while not in string?