检查字符串是否已排序 [英] Check if a string is sorted

查看:68
本文介绍了检查字符串是否已排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简化的"12345"字符串,已排序.字符串可以包含数字(0-9)或字母(a-z).如果混合使用自然排序顺序.我需要一种方法来验证这是否正确.

I have a string, simplified "12345" which is sorted. The string couild contain Digits (0-9) or letters (a-z). In case of a mixed use the natural sort order. I need a method to verify if this is true.

尝试使用linq技术:

Attempt with linq technique:

string items1 = "2349"; //sorted
string items2 = "2476"; //not sorted, 6<>7

bool sorted1 = Enumerable.SequenceEqual(items1.OrderBy(x => x), items1); //true
bool sorted2 = Enumerable.SequenceEqual(items2.OrderBy(x => x), items2); //false

但排序顺序也可能是降序.

but there could be also a descending sort order.

那有没有更好的方法

string items3 = "4321";
bool sorted3 = Enumerable.SequenceEqual(items3.OrderBy(x => x), items3) || Enumerable.SequenceEqual(items3.OrderByDescending(x => x), items3);

检查字符串是否已排序?也许有一些内置的解决方案?

to check if a string is sorted? Maybe some built in solution?

推荐答案

我曾经不得不检查与您的情况类似的事情,但数据流庞大,因此性能非常重要.我想出了这个性能很好的小型扩展类:

I once had to check something similar to your case but with huge data streams, so performance was important. I came up with this small extension class which performs very well:

public static bool IsOrdered<T>(this IEnumerable<T> enumerable) where T: IComparable<T>
{
    using (var enumerator = enumerable.GetEnumerator())
    {
        if (!enumerator.MoveNext())
            return true; //empty enumeration is ordered

        var left = enumerator.Current;
        int previousUnequalComparison = 0;

        while (enumerator.MoveNext())
        {
            var right = enumerator.Current;
            var currentComparison = left.CompareTo(right);

            if (currentComparison != 0)
            {
                if (previousUnequalComparison != 0
                    && currentComparison != previousUnequalComparison)
                    return false;

                previousUnequalComparison = currentComparison;
                left = right;
            }
        }
    }

    return true;
}

使用它显然非常简单:

var items1 = "2349";
var items2 = "2476"; //not sorted, 6<>7
items1.IsOrdered(); //true
items2.IsOrdered(); //false

这篇关于检查字符串是否已排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆