【程序员面试金典】01
  EFTJ6596AiAP 2023年11月02日 60 0

题目

实现一个算法,确定一个字符串 ​s​ 的所有字符是否全都不同。

链接:​https://leetcode.cn/problems/is-unique-lcci/​


解答

思路:如果一个字符第一次出现的下标和最后一次出现不一样,说明出现过不止一次

public class Solution {
public bool IsUnique(string astr) {

bool isUnique = true;
foreach(char item in astr)
{
int preIndex = astr.IndexOf(item);
int lastIndex = astr.LastIndexOf(item);
if (preIndex != lastIndex) isUnique = false;
}
return isUnique;
}
}


语法点

IndexOf

​https://docs.microsoft.com/en-us/dotnet/api/system.array.indexof?view=net-6.0​

LastIndexOf

​https://docs.microsoft.com/en-us/dotnet/api/system.array.lastindexof?view=net-6.0​


结果

【程序员面试金典】01_c++

C++的代码和这个思路是一致的,代码参考如下:

class Solution {
public:
bool isUnique(string astr) {
for (int i =0; i<astr.size(); i++)
{
if (astr.find(astr[i])!= astr.rfind(astr[i]))
{
return false;
}
}
return true;
}
};
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

EFTJ6596AiAP