C# Stack Solution


  • 0
    G
    // 388. Longest Absolute File Path
    
    public class Solution {
        public int LengthLongestPath(string input) {
            string[] arrInput = input.Split('\n');
    		
    		Stack pathStack = new Stack(0);
    		
    		int maxLen = 0;
    		
    		int currentStackLen = 0;
    		
    		foreach (string subInput in arrInput)
    		{
    			if(string.IsNullOrEmpty(subInput))
    			{
    				continue;
    			}
    			
    			// The zero-based index position of value if that character is found, 
    			//or -1 if it is not.
    			int tabCount = subInput.LastIndexOf('\t') + 1; 
    			
    			string name = null;
    			if(tabCount > 1)
    			{
    				name = subInput.Substring(tabCount - 1);
    			}
    			else
    			{
    				name = subInput;
    			}
    			
    			while(tabCount < pathStack.Count)
    			{
    				string popItem = (string)pathStack.Pop();
    				currentStackLen -= popItem.Length;
    			}
    				
    			pathStack.Push(name);
    			currentStackLen += name.Length;
    
    			if(name.Contains('.'))
    			{
    				maxLen = (currentStackLen > maxLen ) ? currentStackLen : maxLen;
    			}	
    		}
    		
    		return maxLen;
        }
    }
    

Log in to reply
 

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