zoukankan      html  css  js  c++  java
  • lintcode:Unique Characters 判断字符串是否没有重复字符

    题目:

    判断字符串是否没有重复字符

    实现一个算法确定字符串中的字符是否均唯一出现

    样例

    给出"abc",返回 true

    给出"aab",返回 false

    挑战

    如果不使用额外的存储空间,你的算法该如何改变?

    解题:

    定义一个集合最简单。

    Java程序:

    public class Solution {
        /**
         * @param str: a string
         * @return: a boolean
         */
        public boolean isUnique(String str) {
            // write your code here
            TreeSet set = new TreeSet();
            for(int i=0;i<str.length();i++)
                if(set.add(str.charAt(i))==false)
                    return false;
            return true;
        }
    }
    View Code

    总耗时: 2209 ms

    Java程序:

    public class Solution {
        /**
         * @param str: a string
         * @return: a boolean
         */
        public boolean isUnique(String str) {
            // write your code here
            for(int i=0;i<str.length();i++){
                for(int j=i+1;j<str.length();j++){
                    if(str.charAt(i)==str.charAt(j))
                        return false;
                }
            }
            return true;
        }
    }
    View Code

    总耗时: 1095 ms

    这样应该不算额外存储空间吧,时间复杂度O(n2)

    Python程序:

    利用字典

    class Solution:
        # @param s: a string
        # @return: a boolean
        def isUnique(self, str):
            # write your code here
            d = {}
            for s in str:
                if s not in d:
                    d[s] = 1
                else:
                    return False
            return True
    View Code

    总耗时: 255 ms

  • 相关阅读:
    HDU 3081 Marriage Match II
    HDU 4292 Food
    HDU 4322 Candy
    HDU 4183 Pahom on Water
    POJ 1966 Cable TV Network
    HDU 3605 Escape
    HDU 3338 Kakuro Extension
    HDU 3572 Task Schedule
    HDU 3998 Sequence
    Burning Midnight Oil
  • 原文地址:https://www.cnblogs.com/bbbblog/p/4868946.html
Copyright © 2011-2022 走看看