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

  • 相关阅读:
    3、Ubantu下安装nginx
    2、关于mongodb外部访问不成功的问题
    1. libcurl.so.4: cannot open shared object file: No such file or directory
    Php 笔记
    Jade之Plain Text
    Jade之Mixins
    Jade之Interpolation
    Jade之Template Inheritance
    Jade之Includes
    Jade之Filters
  • 原文地址:https://www.cnblogs.com/theskulls/p/4868946.html
Copyright © 2011-2022 走看看