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

  • 相关阅读:
    分式函数的变换源
    分式之殇
    两条直线的位置关系
    数列专题思维导图
    数列通项公式思维导图
    函数与导数思维导图
    三角函数思维导图
    函数与初等函数思维导图
    集合思维导图
    npm包发布正式和测试版
  • 原文地址:https://www.cnblogs.com/bbbblog/p/4868946.html
Copyright © 2011-2022 走看看