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

  • 相关阅读:
    51nod乘积之和
    Dell服务器安装OpenManage(OMSA)
    Nginx反向代理PHP
    搭建haproxy
    108. Convert Sorted Array to Binary Search Tree
    60. Permutation Sequence
    142. Linked List Cycle II
    129. Sum Root to Leaf Numbers
    118. Pascal's Triangle
    26. Remove Duplicates from Sorted Array
  • 原文地址:https://www.cnblogs.com/theskulls/p/4868946.html
Copyright © 2011-2022 走看看