LeetCode127

题目

给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则:

  • 每次转换只能改变一个字母。

  • 转换过程中的中间单词必须是字典中的单词。


    说明:

  • 如果不存在这样的转换序列,返回 0。

  • 所有单词具有相同的长度。

  • 所有单词只由小写字母组成。

  • 字典中不存在重复的单词。
    你可以假设 beginWord 和 endWord 是非空的,且二者不相同。
    Leetcode刷题——190327

思路

用一个队列去保存,把所有可能结果都去掉以后,剩下得就是最简单的。(容器的遍历删除要用迭代器

代码



    public int ladderLength(String start, String end, HashSet<String> dict) {
     //1.用一个队列保存已经用过的单词,然后 从dict中 删除这个单词
     //2.弹出queue中保存的上一步留有的单词,并进行变换
     //2.1如果存在一个变换,可以使queue中某一个数先变成end;那么直接返回res++
     //2.2否则,在上次变换的基础上再次变换,把上次的单词全部弹出,根据弹出值,加入新值
     //3.res++
     //4.直至等于end或者dict中没有了才停止
     
     int res = 1;
     LinkedList<String> queue = new LinkedList<>();    //queue用于存放已经使用过的单词
     queue.offer(start);
     while(!queue.isEmpty()) { //queue中还有值
        int size = queue.size();

        while(size>0) {
            String s =queue.poll();//从队头删除
            size--;           

            if(isDifferent(s,end)) 
                return res+1;
           
            for(Iterator<String> it = dict.iterator();it.hasNext();) {
                String str = it.next();
                if(isDifferent(s,str)) {
                    queue.offer(str);
                    it.remove();
                }
            }
        }
        res++;
     }
     return 0;
}

    private boolean isDifferent(String s, String end) {
        // TODO Auto-generated method stub
        int count = 0;
        for(int i =0;i<s.length();++i) {
            if(s.charAt(i)!=end.charAt(i))
                count++;
        }
        return count==1?true:false;
    }





LeetCode125验证回文串

题目:

给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。

说明:本题中,我们将空字符串定义为有效的回文串。

思路

只保留字符串中字母和字符,并全部转化为小写,然后验证回文()(用正则化效率比较低)

代码



    public static boolean isPalindrome(String s) {
        s = s.replaceAll("[^a-zA-Z0-9]","").toLowerCase();
        for(int i=0;i<s.length();++i) {
           if(s.charAt(i)!=s.charAt(s.length()-1-i))
               return false;
        }
        return true;
    }





LeetCode121 买卖股票的最佳时机

题目:给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。注意你不能在买入股票前卖出股票。
Leetcode刷题——190327

代码:

1.贪婪算法 O(n2)



public int maxProfit(int[] prices) {
    if(prices.length<2)
        return 0;
    int res = 0;
    for(int i=0;i<prices.length;++i){
        for(int j=i;j<prices.length;++j){
            if(prices[j]-prices[i]>0)
                res =Math.max(res,prices[j]-prices[i]);
        }
    }
    return res;
}

2.动态规划? 保证最大值前找到最小值



    public int maxProfit(int[] prices) {
     if(prices==null||prices.length<2)           
        return 0;       
     int minNum=prices[0],maxPro=0;        
     for(int i=1;i<prices.length;i++){        
        if(prices[i]<minNum)           
            minNum=prices[i];           
        else if(prices[i]>minNum)           
            maxPro=Math.max(maxPro,prices[i]-minNum);    
        }                 
     return maxPro;   
     }

相关文章: