C# solution using IEnumerable


  • 0
    A
    public class NestedIterator {
        private IEnumerator<NestedInteger> Enumerator;
    
        private IEnumerable<NestedInteger> Enumerate(NestedInteger nestedInteger)
        {
            if (nestedInteger.IsInteger())
            {
                yield return nestedInteger;
            }
            else
            {
                foreach (var item in Enumerate(nestedInteger.GetList()))
                {
                    yield return item;
                }
            }
        }
        
        private IEnumerable<NestedInteger> Enumerate(IList<NestedInteger> nestedList)
        {
            foreach (var item in nestedList.Select(x => Enumerate(x)).SelectMany(x => x))
            {
                yield return item;
            }
        }
        
        public NestedIterator(IList<NestedInteger> nestedList) {
            Enumerator = Enumerate(nestedList).GetEnumerator();
        }
    
        public bool HasNext() {
            return Enumerator.MoveNext();
        }
    
        public int Next() {
            return Enumerator.Current.GetInteger();
        }
    }

  • 0
    X

    HasNext should not update the Iterator's state


Log in to reply
 

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