Anyone getting ConcurrentModificationException with Java?


  • 0
    M

    It seems OJ was trying to run my code concurrently, I was getting ConcurrentModificationException until I changed both data structures to their concurrent friendly versions.
    Just thought that might helped someone.

    import java.util.concurrent.*;
    public class Solution {
        
        public int ladderLength(String start, String end, Set<String> dict) {
            Queue<Node> bfs = new ConcurrentLinkedQueue<Node>();
            Set<String> d = new ConcurrentSkipListSet<String>(dict);
            bfs.add(new Node(start, 1));
            while (!bfs.isEmpty()) {
                Node cur = bfs.poll();
                if (validJump(cur.word, end)) return cur.count + 1;
                for (String w: d) {
                    if (validJump(cur.word, w)) {
                        bfs.add(new Node(w, cur.count + 1));
                        d.remove(w);
                    }
                }
            }
            return 0;
        }
    
        private boolean validJump(String start, String end) {
            int count = 0;
            for (int i = 0; i < start.length(); i++) {
                if (start.charAt(i) != end.charAt(i)) count++;
                if (count > 1) return false;
            }
            return count == 1;
        }
        
        private class Node {
            String word;
            int count;
            public Node (String word, int count) {
                this.word = word;
                this.count = count;
            }
        }
    }

Log in to reply
 

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