Simplify path: Expected output equals to Output, why it still says "Wrong Answer" ?


  • 0
    X

    222 / 252 test cases passed.

    Wrong Answer:
    Input: "/."
    Output: "/"
    Expected: "/"

    I also tested my code on visual c++, it passed all the testcases, including the one given by the "wrong answer".

    If it's wrong, at least it should give me a output that's different from the Expected, right?

    My code is here:

    class Solution {
    public:
    	string simplifyPath(string path) {
    		string result = "/"; //consider result as a stack here
    		int i = 1;
    		while (i<path.size()){
    			int countDot = 0;
    			while (i<path.size() && path[i] == '.'){
    				++countDot;
    				++i;
    			}
    			if (countDot>  0){
    				if ((i == path.size() || path[i] == '/')) {
    					if (countDot == 1) {
    					}
    					if (countDot == 2){
    						do{
    							if (result.length() == 1)
    								break;
    							result.pop_back();
    						} while (result.back() != '/');
    					}
    					if (countDot > 2){
    						result.append(countDot, '.');
    					}
    				}
    				else{
    					result.append(countDot, '.');
    				}
    			}
    			if (path[i] == '/' && result.back() == '/'){
    			}
    			else{
    				result.push_back(path[i]);
    			}
    			i++;
    		}
    		if (result.back() == '/' && result.length() > 1) result.pop_back();
    		return result;
    	}
    

    };


  • 0
    X
    This post is deleted!

  • 2
    S

    "If it's wrong, at least it should give me a output that's different from the Expected, right?" Yes, but sometimes the wrong result would LOOK the same as the correct output while they are actually not. This is exactly what happened to your case. Let's see what you have done:

    while (i<path.size() && path[i] == '.'){
                ++countDot;
                ++i;
            }
    

    So for the input '/.', we have i = 2 when the loop terminates. This part is fine by itself. However, from this point on, you should no longer use 'path[i]' since it is already out of bound. Unfortunately, shortly after, you have:

    if (path[i] == '/' && result.back() == '/'){
            }
            else{
                result.push_back(path[i]);
            }
    

    'path[i]' in this piece of code would cause undefined behaviour. In your case, it probably returns an unprintable character, which does not equal to '/', so it is added to result. In the end, your
    result is actually "/" + (a garbage character), which is different from the expected result "/".


Log in to reply
 

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