class Solution {
public:
string morseAlpabet[26] = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." };
int uniqueMorseRepresentations(vector<string>& words) {
string words2morse[200] = {};
int wordsNum = 0;
//word count
while (int(words[wordsNum].length())!=0) {
wordsNum += 1;
}
//count word length
int wordLength = 0;
string morseCodesThisWord = "";
for (int i = 0; i < wordsNum; i++) {
wordLength = words[i].length();
morseCodesThisWord = "";
for (int j = 0; j < wordLength; j++) {
int wordLetterOrder = int(words[i][j] - 'a');
morseCodesThisWord += morseAlpabet[wordLetterOrder];
}
words2morse[i] = morseCodesThisWord;
}
set<string> morseKind(words2morse, words2morse + wordsNum);
return int(morseKind.size());
}
};
此代码在Visual Studio 2017本地环境中运行时效果很好,但是在Leetcode中运行时,它会引发Runtimr错误,例如“对绑定到'value_type'类型的空指针的引用”,我不知道它是否可以接受,但我必须先处理此错误。有人可以帮忙吗?请!
答案 0 :(得分:0)
好吧,我终于找到了:(
words[wordsNum]
是错误的方式,我们应该直接使用words.size()
。在像这样更改代码之后。被接受了。
class Solution {
public:
string morseAlpabet[26] = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." };
int uniqueMorseRepresentations(vector<string>& words) {
string words2morse[200] = {};
//count word length
int wordLength = 0;
string morseCodesThisWord = "";
for (int i = 0; i < words.size(); i++) {
wordLength = words[i].length();
morseCodesThisWord = "";
for (int j = 0; j < wordLength; j++) {
int wordLetterOrder = int(words[i][j] - 'a');
morseCodesThisWord += morseAlpabet[wordLetterOrder];
}
words2morse[i] = morseCodesThisWord;
}
set<string> morseKind(words2morse, words2morse + words.size());
return int(morseKind.size());
}
};