WEILD!!! expected is "c" Output is "c" , Input is ["c","c"].


  • 0
    P

    Here is my code:

    class Solution {
    public:
    string longestCommonPrefix(vector<string> &strs) {
        
    	int len = strs.size();
    	if (len == 1) {
    		return strs[0];
    	}
    	if (len == 0) {
    		return "";
    	}
    	
    	string prefix= strs[0];
    	for (int i = 1 ; i < len; i++) {
    		if (strs[i].length() == 0) {
    			return "";
    		}
    		
    		string tempString;
    		int j =0;
    		while (prefix[j] == strs[i][j]) {
    			tempString.push_back(prefix[j]);
    			j++;
    		}
    		prefix = tempString;
    	}
    	return prefix;
    }
    };

  • 0
    M

    Assuming this is exactly what you submitted for approval, try printing out tempString as a series of ints (convert char to int). You almost certainly have unprintable characters in the string causing the equals function to fail.


  • 0
    P

    Okay, My code was accepted by using another way to save the common prefix string, BUT this code is running normally also, you can test this code. I don't know why this code is rejected:the answer is right. Thanks for your reply anyway.


  • 0
    M

    When you tried my suggestion on the input you've given, what ints did you get? Just 99? Or were there others?


  • 0
    T

    I think I see the problem. In your while loop, while (prefix[j] == strs[i][j]) { ... }, if prefix is equal to strs[i], you will run past the end of the string and start adding garbage to tempString.

    Also note that prior to C++11, tempString[tempString.length()] may not be equal to \0. Just throwing it out there in case you think of fixing the problem by incrementing j until you hit \0.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.