LeetCode刷题总结--DFS与字符串处理

388. Longest Absolute File Path
"dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"这个字符串序列是由文件目录树的深度优先搜索(先根遍历)得到的,所以需要借助栈来进行解析这个字符串得到所有全路径,从而比较全路径字符串的长度。这里要注意的是一个子文件夹下可能还包含子文件夹和文件,所以借助单调栈(每个当前相对路径的深度或层次是单调递增的)。

import javafx.util.Pair;
import java.util.LinkedList;
import java.util.Stack;

public class LongestAbsoluteFilePath {

    public static int lengthLongestPath(String input) {
        String[] lists = input.split("\n");
        LinkedList> table = new LinkedList<>();
        for (String s : lists) {
            int count = 0;
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == '\t')
                    count++;
                else
                    break;
            }
            Pair tmp = new Pair<>(s.substring(count), count);
            table.add(tmp);
        }

        Stack> stack = new Stack<>();
        int ret = 0;
        int curr = 0;
        int wc = 0;
        for (Pair pair : table) {

            String key = (String) pair.getKey();
            Integer val = (Integer) pair.getValue();
            while (!stack.isEmpty() && stack.peek().getValue() >= val) {
                String s = stack.pop().getKey();
                curr -= s.length();
                wc -= 1;
            }
            stack.add(pair);
            curr += key.length();
            wc += 1;

            if (key.contains("."))
                ret = Math.max(ret, curr + wc - 1);
        }
        return ret;
    }

    public static void main(String[] args) {
        String ex="dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext";
        System.out.println(lengthLongestPath(ex));
        String[] tmp=ex.split("\n");
        for (String s:tmp)
            System.out.println(s);
    }
}

386. Lexicographical Numbers
算法一:字符串排序O(n+nlogn)

class Solution {
    
    public List lexicalOrder(int n) {
        
        LinkedList list=new LinkedList<>();
        String[] vals=new String[n];
        for(int i=1;i<=n;i++)
            vals[i-1]=String.valueOf(i);
        Arrays.sort(vals);
        for(String val:vals)
            list.add(Integer.valueOf(val));
        return list;
    }
}

算法二:栈

class Solution {
    
    public List lexicalOrder(int n) {
        
        LinkedList ret = new LinkedList<>();
        Stack stack = new Stack<>();
        for (int i = n <= 9 ? n : 9; i > 0; i--) {
            stack.push(i);
        }
        while (!stack.isEmpty()){
            int cur=stack.pop();
            ret.add(cur);
            
            for(int j=9;j>=0;j--){
                int val=cur*10+j;
                if(val<=n)
                    stack.push(val);
            }
        }
        return ret;
    }
}

算法三:DFS,这种解法特别优美

class Solution {
    
    public static LinkedList ret;
    public List lexicalOrder(int n) {
        
        ret=new LinkedList<>();
        for(int i=1;i<=9;i++)
        {
            if(i<=n)
            {
                ret.add(i);
                dfs(i,n);
            }    
        }
        return ret;
    }
    
    public static void dfs(int num,int n){
        if(num>n)
            return;
        for(int i=0;i<=9;i++)
        {
            int t=num*10+i;
            if(t<=n){
                ret.add(t);
                dfs(t,n);
            }
            else
                break;
        }
    }   
}

208. Implement Trie (Prefix Tree)
在算法导论上看到这种数据结构,真的优美极了!

class Trie {

    
    private TrieNode root;
    
    class TrieNode{
        
        private TrieNode[] links;
        private final int R=26;
        private boolean isEnd;
        
        public TrieNode(){
            links=new TrieNode[R];
        }
        
        public boolean containsKey(char c){
            return links[c-'a']!=null;
        }
        
        public TrieNode get(char c){
            return links[c-'a'];
        }
        
        public void put(char c,TrieNode node){
            links[c-'a']=node;
        }
        
        public void setEnd(){
            isEnd=true;
        }
    }
    /** Initialize your data structure here. */
    public Trie() {
        root=new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode node=root;
        for(int i=0;i

211. Add and Search Word - Data structure design

class WordDictionary {

    public TrieNode root;

    class TrieNode {

        private TrieNode[] links;
        private final int R = 26;
        private boolean isEnd;

        public TrieNode() {
            links = new TrieNode[R];
        }

        public boolean containsKey(char c) {
            return links[c - 'a'] != null;
        }

        public TrieNode get(char c) {
            return links[c - 'a'];
        }

        public void put(char c, TrieNode node) {
            links[c - 'a'] = node;
        }

        public void setEnd() {
            isEnd = true;
        }
    }
    
    /** Initialize your data structure here. */
    public WordDictionary() {
        root = new TrieNode();
    }
    
    /** Adds a word into the data structure. */
    public void addWord(String word) {
        TrieNode node = this.root;
        for (int i = 0; i < word.length(); i++) {
            char curChar = word.charAt(i);
            if (!node.containsKey(curChar))
                node.put(curChar, new TrieNode());
            node = node.get(curChar);
        }
        node.isEnd = true;
    }
    
    private boolean search(TrieNode node, String word, int idx) {
        if (idx == word.length())
            return node.isEnd;
        char c = word.charAt(idx);
        boolean flag = false;

        if (c == '.') {
            for (TrieNode tmp : node.links) {
                if (tmp != null)
                    flag = flag || search(tmp, word, idx + 1);
            }
        } else if (node.get(c) == null){
            return false;
        }
        else
            return search(node.get(c), word, idx + 1);
        return flag;

    }
    
    /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
    public boolean search(String word) {
        return search(this.root, word, 0);
    }
}

/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary obj = new WordDictionary();
 * obj.addWord(word);
 * boolean param_2 = obj.search(word);
 */

你可能感兴趣的:(LeetCode刷题总结--DFS与字符串处理)