找到字符串中最高的重复字符和重复字符的计数

时间:2014-02-26 10:07:06

标签: ios nsstring nsarray

我需要获得字符串中最高的重复字符和重复字符的计数。 为此,我将字符串中的每个字符存储在数组中,并使用for循环获取每个字符和计数。是否有任何其他委托方法来找到它来减少代码?

例如

NSRange theRange = {0, 1}; //{location, length}
NSMutableArray * array = [NSMutableArray array];
for ( NSInteger i = 0; i < [myFormattedString length]; i++) {
    theRange.location = i;
    [array addObject:[myFormattedString substringWithRange:theRange]];
}
int countForChar = 0;
for (int i=0; i<[array count]; i++) {
    NSString *firstCharacter = [array objectAtIndex:i];
    for (int j=1; j< [array count]; j++) {
        if ([firstCharacter isEqualToString:[array objectAtIndex:j]]) {
            countForChar = countForChar + 1;
        }
    }
    NSLog(@"The Charcter is %@ The count is %d", firstCharacter, countForChar);
    countForChar = 0;
}

提前致谢...

4 个答案:

答案 0 :(得分:1)

这是我的代码可能不够好,但我认为它是最快的

NSString *myFormattedString = @"oksdflajdsfd";

    NSMutableDictionary *lettersCount = [[NSMutableDictionary alloc] init];
    for (NSInteger i = 0; i < [myFormattedString length]; i++) {
        unichar charAtIndex = [myFormattedString characterAtIndex:i];
        NSNumber *countForThisChar = [lettersCount objectForKey:[NSString stringWithFormat:@"%c",charAtIndex]];
        int count = 1;
        if(countForThisChar) {
            count = [countForThisChar integerValue] + 1;
            [lettersCount setObject:@(count) forKey:[NSString stringWithFormat:@"%c",charAtIndex]];
        } else {
            // not added yet, add it with 1 count
            [lettersCount setObject:@(count) forKey:[NSString stringWithFormat:@"%c",charAtIndex]];
        }
    }

    // for now the work is O(n)

    // ignoring the work of this cycle or consider it as O(1)
    NSString *mostFrequentChar = nil;
    NSInteger maxCount = 0;
    for(NSString *oneChar in lettersCount.keyEnumerator) {
        NSNumber *count = [lettersCount objectForKey:oneChar];
        if([count integerValue] > maxCount) {
            mostFrequentChar = oneChar;
            maxCount = [count integerValue];
        }
    }

    NSLog(@"the char %@ met for %d times", mostFrequentChar, maxCount);

请记住,在NsDictionary中搜索对象的平均情况为O(1)。

答案 1 :(得分:1)

这是一个可以正常使用任何字符串并具有线性时间复杂度的示例。这使用NSCountedSet,这可能非常有用。

NSString* string = @"This is a very wonderful string. Ølsen & ジェイソン";
NSCountedSet* characterCounts = [[NSCountedSet alloc] init];
// This ensures that we deal with all unicode code points correctly
[string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
  [characterCounts addObject:substring];
}];
NSString* highestCountCharacterSequence = nil;
NSUInteger highestCharacterCount = 0;
for (NSString* characterSequence in characterCounts) {
  NSUInteger currentCount = [characterCounts countForObject:characterSequence];
  if (currentCount > highestCharacterCount) {
    highestCountCharacterSequence = characterSequence;
    highestCharacterCount = currentCount;
  }
}
NSLog(@"Highest Character Count is %@ with count of %lu", highestCountCharacterSequence, (unsigned long)highestCharacterCount);

可悲的是,我的愚蠢示例字符串最终会出现空格字符,这是最重复的:)

答案 2 :(得分:1)

因为字符串可能有多个char具有相同的重复次数,所以这是我的解决方案:

- (NSArray *)mostCharInString:(NSString *)string count:(int *)count{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    int len = string.length;
    NSRange theRange = {0, 1};
    for (NSInteger i = 0; i < len; i++) {
        theRange.location = i;
        NSString *charStr = [string substringWithRange:theRange];
        int preCount = 0;
        if ([dict objectForKey:charStr]) {
            preCount = [[dict objectForKey:charStr] unsignedIntegerValue];
        }
        [dict setObject:@(preCount+1) forKey:charStr];
    }
    NSArray *sortValues = [[dict allValues] sortedArrayUsingSelector:@selector(compare:)];
    *count = [[sortValues lastObject] unsignedIntegerValue];
    return  [dict allKeysForObject:@(*count)];
}

如何使用和测试:

int mostRepeatCount = 0;
NSArray *mostChars = nil;
mostChars = [self mostCharInString:@"aaabbbcccc" count:&mostRepeatCount];
NSLog(@"count:%d char:%@", mostRepeatCount, mostChars);

结果是:

count:4 char:(
    c
)

尝试:

mostChars = [self mostCharInString:@"aaabbbccccdddd" count:&mostRepeatCount];

结果是:

count:4 char:(
    d,
    c
)

希望能帮到你。

答案 3 :(得分:0)

每个字符都可以通过其int值显示。制作NSArray的实例,其中 n 大小(字符串可以包含n个唯一字符数)。循环遍历字符串并在每个循环中在数组中添加+1(int)字符索引。当你完成数组中具有最大值的字符时,是最重复的字符。