LintCode: Unique Characters

本文提供两种使用C++检查字符串中字符是否全部唯一的算法实现。一种时间复杂度为O(n²),空间复杂度为O(0);另一种时间复杂度为O(n),空间复杂度为O(n)。通过这两种不同的方法,可以有效地解决字符串中字符重复的问题。

C++,

time: O(n^2)

space: O(0)

复制代码
class Solution {
public:
    /**
     * @param str: a string
     * @return: a boolean
     */
    bool isUnique(string &str) {
        // write your code here
        for (int i=0; i<str.size(); i++) {
            for (int j=i+1; j<str.size(); j++) {
                if (str[i] == str[j]) {
                    return false;
                }
            }
        }
        return true;
    }
};
复制代码

C++,

time: O(n)

space: O(n)

复制代码
 1 class Solution {
 2 public:
 3     /**
 4      * @param str: a string
 5      * @return: a boolean
 6      */
 7     bool isUnique(string &str) {
 8         // write your code here
 9         string tmp;
10         for (int i=0; i<str.size(); i++) {
11             if (-1 == tmp.find(str[i])) {
12                 tmp.push_back(str[i]);
13             } else {
14                 return false;
15             }
16         }
17         return true;
18     }
19 };
复制代码

 

本文转自ZH奶酪博客园博客,原文链接:http://www.cnblogs.com/CheeseZH/p/4999745.html,如需转载请自行联系原作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值