Python 查找字符串中第一个不重复的字符
我阅读了一篇关于求职面试问题的文章,为以下内容编写了一些代码: 编写一个有效的函数来查找中的第一个非重复字符 一串。例如,“total”中的第一个非重复字符是 “o”和“teeter”中的第一个非重复字符是“r”。讨论 你的算法的效率 我用Python提出了这个解决方案;但是,我相信有很多更好的方法可以做到这一点Python 查找字符串中第一个不重复的字符,python,algorithm,Python,Algorithm,我阅读了一篇关于求职面试问题的文章,为以下内容编写了一些代码: 编写一个有效的函数来查找中的第一个非重复字符 一串。例如,“total”中的第一个非重复字符是 “o”和“teeter”中的第一个非重复字符是“r”。讨论 你的算法的效率 我用Python提出了这个解决方案;但是,我相信有很多更好的方法可以做到这一点 word="googlethis" dici={} #build up dici with counts of characters for a in word: try:
word="googlethis"
dici={}
#build up dici with counts of characters
for a in word:
try:
if dici[a]:
dici[a]+=1
except:
dici[a]=1
# build up dict singles for characters that just count 1
singles={}
for i in dici:
if dici[i]==1:
singles[i]=word.index(i)
#get the minimum value
mini=min(singles.values())
#find out the character again iterating...
for zu,ui in singles.items():
if ui==mini:
print zu
有没有更简洁有效的答案
sorted(word,key=lambda x:(word.count(x),word.index(x)) )[0]
我想
还是DSM的一致性
next(c for c in word if word.count(c) == 1)
哪一个稍微更有效率
>>> word = "teeter"
>>> sorted(word,key=lambda x:(word.count(x),word.index(x)) )[0]
'r'
>>> word = "teetertotter"
>>> sorted(word,key=lambda x:(word.count(x),word.index(x)) )[0]
'o'
>>> word = "teetertotterx"
>>> sorted(word,key=lambda x:(word.count(x),word.index(x)) )[0]
'o'
编辑:如果您想在不使用诸如计数器之类的帮助程序的情况下实现相同的功能:
def firstNonRep(word):
count = {}
for c in word:
if c not in count:
count[c] = 0
count[c] += 1
for c in word:
if count[c] == 1:
return c
从集合导入defaultdict
word=“googlethis”
dici=defaultdict(int)
#用字符数建立dici
一句话:
如果dici[a]:
dici[a]+=1
一句话:
如果didic[a]<2:
归还
那不行吗?我的解决方案。我说不出它有多高效;我想它只运行了n^2次
>>> def fst_nr(s):
... collection = []
... for i in range(len(s)):
... if not s[i] in collection and not s[i] in s[i+1:]:
... return s[i]
... else:
... collection+=[s[i]]
...
>>> fst_nr("teeter")
'r'
>>> fst_nr("floccinaucinihilipilification")
'u'
>>> fst_nr("floccinacinihilipilification")
'h'
>>> fst_nr("floccinaciniilipilification")
'p'
>>> fst_nr("floccinaciniiliilification")
't'
>>> fst_nr("floccinaciniiliilificaion")
>>>
对于简单的堆栈noob有什么建议吗?这里的想法是用一些默认值初始化数组,例如0。当您在字符串中遇到一个特定字符时,您只需在最初定义的数组中使用该字符的ASCII值来增加计数器
在传递字符串时,必须更新数组中字符的相应计数器。现在需要再次遍历数组,并检查是否有任何值等于1,如果有,只需将该字符作为给定字符串中的第一个非重复字符返回即可
class FindFirstUniqueChar
{
private static char ReturnFirstUniqueChar(string sampleString)
{
// Initialize a sample char array and convert your string to char array.
char[] samplechar = sampleString.ToCharArray();
// The default array will have all value initialized as 0 - it's an int array.
int[] charArray = new int[256];
// Go through the loop and update the counter in respective value of the array
for (int i = 0; i < samplechar.Length; i++)
{
charArray[samplechar[i]] = charArray[samplechar[i]] + 1;
}
// One more pass - which will provide you the first non-repeated char.
for (int i = 0; i < charArray.Length; i++)
{
if (charArray[samplechar[i]] == 1)
{
return samplechar[i];
}
}
// Code should not reach here. If it returns '\0'
// that means there was no non-repeated char in the given string.
return '\0';
}
static void Main(string[] args)
{
Console.WriteLine("The First Unique char in given String is: " +
ReturnFirstUniqueChar("ABCA"));
Console.ReadLine();
}
}
类FindFirstUniqueChar
{
私有静态字符ReturnFirstUniqueChar(字符串sampleString)
{
//初始化示例字符数组并将字符串转换为字符数组。
char[]samplechar=sampleString.ToCharArray();
//默认数组将所有值初始化为0-这是一个int数组。
int[]charArray=新int[256];
//遍历循环并在数组的相应值中更新计数器
for(int i=0;i
我只提供了一个示例代码。它不包括错误检查和边缘情况。
对于那些有兴趣知道给定算法的时间复杂度的人来说,它是
O(N)+O(N)=O(2N),接近O(N)。它确实使用了额外的内存空间。
欢迎您的反馈 我认为最坏的情况是O(n^2),但对我来说很清楚:
def firstNonRep(word):
"""the first non-repeating character in a string: "ABCA" -> B """
for (i, c) in enumerate(word):
residual = word[i+1:]
if not c in residual:
return c
蟒蛇;我想是O(N+N)
在爪哇,
1) 创建字符计数哈希映射。
对于每个字符,如果字符中没有存储值,请将其设置为1。
否则,将字符的值增加1
2) 然后我扫描了每个字符的字符串。
如果hashmap中的计数为1,则返回字符。
如果没有字符具有计数1,则返回null
package com.abc.ridhi;
import java.util.HashMap;
import java.util.Scanner;
public class FirstNonRepeated {
public static void main(String[] args) {
System.out.println(" Please enter the input string :");
Scanner in = new Scanner(System.in);
String s = in.nextLine();
char c = firstNonRepeatedCharacter(s);
System.out.println("The first non repeated character is : " + c);
}
public static Character firstNonRepeatedCharacter(String str) {
HashMap<Character, Integer> map1 = new HashMap<Character, Integer>();
int i, length;
Character c;
length = str.length();
// Scan string and build hashmap
for (i = 0; i < length; i++) {
c = str.charAt(i);
if (map1.containsKey(c)) {
// increment count corresponding to c
map1.put(c, map1.get(c) + 1);
} else {
map1.put(c, 1);
}
}
// Search map in order of string str
for (i = 0; i < length; i++) {
c = str.charAt(i);
if (map1.get(c) == 1){
return c;
}
}
return null;
}
}
package com.abc.ridhi;
导入java.util.HashMap;
导入java.util.Scanner;
公共类第一次非重复{
公共静态void main(字符串[]args){
System.out.println(“请输入字符串:”);
扫描仪输入=新扫描仪(系统输入);
字符串s=in.nextLine();
字符c=第一个非重复字符;
System.out.println(“第一个非重复字符是:“+c”);
}
公共静态字符firstNonRepeatedCharacter(字符串str){
HashMap map1=新的HashMap();
int i,长度;
字符c;
长度=str.length();
//扫描字符串并构建hashmap
对于(i=0;i
获取解决方案的三行python代码:
word="googlethis"
processedList = [x for x in word if word.count(x)==1]
print("First non-repeated character is: " +processedList[0])
或者
下面的代码只遍历字符串一次。这是一个简单易行的问题解决方案,但同时也降低了空间复杂性
def firstNonRepeating(a):
inarr = []
outarr = []
for i in a:
#print i
if not i in inarr:
inarr.append(i)
outarr.append(i)
elif i in outarr:
outarr.remove(i)
else:
continue
return outarr[0]
a = firstNonRepeating(“Your String”)
print a
这个怎么样 因为我们需要第一个非重复字符,所以最好使用集合中的OrderedDict,因为dict不能保证键的顺序
from collections import OrderedDict
dict_values = OrderedDict()
string = "abcdcd"
for char in string:
if char in dict_values:
dict_values[char] += 1
else:
dict_values[char] = 1
for key,value in dict_values.items():
if value == 1:
print ("First non repeated character is %s"%key)
break
else:
pass
def FIRSTNOTREPLATING字符:
对于s中的c:
如果s.find(c)=s.rfind(c):
返回c
以更优雅的方式返回“\p>”
str = "aabcbdefgh"
lst = list(str)
for i in [(item, lst.count(item)) for item in set(lst)]:
if i[1] == 1:
print i[0],
def NotRepeatingCharacter(s):
for c in s:
if s.find(c) == s.rfind(c):
return c
return '_'
公共类优先重复和非重复元素{
/**
*
* @param elements
* @return
*/
private int firstRepeatedElement(int[] elements) {
int firstRepeatedElement = -1;
if(elements!=null && elements.length>0) {
Set<Integer> setOfElements = new HashSet<>();
for(int i=elements.length-1;i>=0;i--){
if(setOfElements.contains(elements[i])) {
firstRepeatedElement = elements[i];
} else {
setOfElements.add(elements[i]);
}
}
}
return firstRepeatedElement;
}
private int firstNonRepeatedHashSet(int [] elements) {
int firstNonRepatedElement = -1;
Set<Integer> hashOfElements = new HashSet<>();
if(elements!=null && elements.length>0) {
for(int i=elements.length-1;i>=0;i--) {
if(!hashOfElements.contains(elements[i])) {
hashOfElements.add(elements[i]);
firstNonRepatedElement = elements[i];
}
}
}
return firstNonRepatedElement;
}
/**
* @param args
*/
public static void main(String[] args) {
FirstRepeatingAndNonRepeatingElements firstNonRepeatingElement =
new FirstRepeatingAndNonRepeatingElements();
int[] input = new int[]{1,5,3,4,3,5,6,1};
int firstRepeatedElement = firstNonRepeatingElement.
firstRepeatedElement(input);
System.out.println(" The First Repating Element is "
+ firstRepeatedElement);
int firstNonRepeatedElement = firstNonRepeatingElement.
firstNonRepeatedHashSet(input);
System.out.println(" The First Non Repating Element is "
+ firstNonRepeatedElement);
}
/**
*
*@param元素
*@返回
*/
私有int firstRepeatedElement(int[]元素){
int firstRepeatedElement=-1;
if(elements!=null&&elements.length>0){
Set-setOfElements=new-HashSet();
对于(int i=elements.length-1;i>=0;i--){
if(元素集合包含(元素[i])){
firstRepeatedElement=元素[i];
def firstnonrecur(word):
for c in word:
if word.count(c) == 1:
print(c)
break
firstnonrecur('google')
from collections import OrderedDict
dict_values = OrderedDict()
string = "abcdcd"
for char in string:
if char in dict_values:
dict_values[char] += 1
else:
dict_values[char] = 1
for key,value in dict_values.items():
if value == 1:
print ("First non repeated character is %s"%key)
break
else:
pass
def non_repeating(given_string):
try:
item = [x for x in given_string[:] if given_string[:].count(x) == 1][0]
except:
return None
else:
return item
# NOTE: The following input values will be used for testing your solution.
print non_repeating("abcab") # should return 'c'
print non_repeating("abab") # should return None
print non_repeating("aabbbc") # should return 'c'
print non_repeating("aabbdbc") # should return 'd'
str = "aabcbdefgh"
lst = list(str)
for i in [(item, lst.count(item)) for item in set(lst)]:
if i[1] == 1:
print i[0],
def NotRepeatingCharacter(s):
for c in s:
if s.find(c) == s.rfind(c):
return c
return '_'
enter code here
/**
*
* @param elements
* @return
*/
private int firstRepeatedElement(int[] elements) {
int firstRepeatedElement = -1;
if(elements!=null && elements.length>0) {
Set<Integer> setOfElements = new HashSet<>();
for(int i=elements.length-1;i>=0;i--){
if(setOfElements.contains(elements[i])) {
firstRepeatedElement = elements[i];
} else {
setOfElements.add(elements[i]);
}
}
}
return firstRepeatedElement;
}
private int firstNonRepeatedHashSet(int [] elements) {
int firstNonRepatedElement = -1;
Set<Integer> hashOfElements = new HashSet<>();
if(elements!=null && elements.length>0) {
for(int i=elements.length-1;i>=0;i--) {
if(!hashOfElements.contains(elements[i])) {
hashOfElements.add(elements[i]);
firstNonRepatedElement = elements[i];
}
}
}
return firstNonRepatedElement;
}
/**
* @param args
*/
public static void main(String[] args) {
FirstRepeatingAndNonRepeatingElements firstNonRepeatingElement =
new FirstRepeatingAndNonRepeatingElements();
int[] input = new int[]{1,5,3,4,3,5,6,1};
int firstRepeatedElement = firstNonRepeatingElement.
firstRepeatedElement(input);
System.out.println(" The First Repating Element is "
+ firstRepeatedElement);
int firstNonRepeatedElement = firstNonRepeatingElement.
firstNonRepeatedHashSet(input);
System.out.println(" The First Non Repating Element is "
+ firstNonRepeatedElement);
}
a = "GGGiniiiiGinaaaPrrrottiijayi"
count = [0]*256
for ch in a: count[ord(ch)] +=1
for ch in a :
if( count[ord(ch)] == 1 ):
print(ch)
break
# 1st non repeating character
pal = [x for x in a if a.count(x) == 1][0]
print(pal)
d={}
for ch in a: d[ch] = d.get(ch,0)+1
aa = sorted(d.items(), key = lambda ch :ch[1])[0][0]
print(aa)
input_str = "interesting"
#input_str = "aabbcc"
#input_str = "aaaapaabbcccq"
def firstNonRepeating(param):
counts = {}
for i in range(0, len(param)):
# Store count and index repectively
if param[i] in counts:
counts[param[i]][0] += 1
else:
counts[param[i]] = [1, i]
result_index = len(param) - 1
for x in counts:
if counts[x][0] == 1 and result_index > counts[x][1]:
result_index = counts[x][1]
return result_index
result_index = firstNonRepeating(input_str)
if result_index == len(input_str)-1:
print("no such character found")
else:
print("first non repeating charater found: " + input_str[result_index])
# I came up with another solution but not efficient comment?
str1 = "awbkkzafrocfbvwcqbb"
list1 = []
count = 0
newlen = len(str1)
find = False
def myfun(count, str1, list1, newlen):
for i in range(count, newlen):
if i == 0:
list1.append(str1[i])
else:
if str1[i] in list1:
str1 = str1.translate({ord(str1[i]): None})
print(str1)
newlen = len(str1)
count =0
i = count
list1.pop()
myfun(count,str1,list1,newlen)
else:
pass
if str1.find(list1[0], 1, len(str1)) != -1 :
pass
else:
print(list1[0]+" is your first non repeating character")
exit()
myfun(count, str1, list1, newlen)
def findFirstUniqueChar(s):
d = {}
for c in s:
if c in d:
d[c] += 1
else:
d[c] = 1
for c in s:
if d[c] == 1:
return s.index(c)
return -1
import java.util.LinkedHashMap;
public class FirstNonRepeatedCharacter {
public static void main(String[] args) {
String str = "sasasasafng";
firstNonRepeatedCharacterUsingCollection(str);
}
private static void firstNonRepeatedCharacterUsingCollection(String str) {
LinkedHashMap<Character, Integer> hm = new LinkedHashMap<Character, Integer>();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (hm.containsKey(ch)) {
hm.put(ch, hm.get(ch) + 1);
} else {
hm.put(ch, 1);
}
}
for (Character c : hm.keySet()) {
if (hm.get(c) == 1) {
System.out.println(c);
return;
}
}
}
}