字符串比较相同顺序的字符个数

发布于 2024-12-13 18:49:43 字数 324 浏览 5 评论 0原文

Str A = "abcdef"
Str B = "abcdf"

需要一个返回 5(即匹配的字符数)的函数(stA,stB),请注意这些字符需要具有相同的顺序。

例如:

Str A = "abcdef"
Str B = "fedcba",

function(stA, stB) 只会为 'a' 返回 1

伪代码很好...

哦,顺便说一句,考虑到我所有的字符串都将有 <= 40 个字符,O(n ^2) 甚至可能比 O(41n) 算法更好。

I have

Str A = "abcdef"
Str B = "abcdf"

I need a function(stA, stB) that returns 5 (ie. the number of characters matched), note that these characters need to be in same order.

For example:

Str A = "abcdef"
Str B = "fedcba",

function(stA, stB) would only return 1 for the 'a'

Pseudo code is good...

Oh btw given that all my strings will have <= 40 characters, O(n^2) might even be better than a O(41n) algorithm..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

悲喜皆因你 2024-12-20 18:49:43

我还没有完全测试它,但这似乎对您的测试用例有效(在 JavaScript 中):

function compare(a, b)
{
    var aChars = a.split('');
    var bChars = b.split('');

    var matches = [];
    var bStart = 0;

    for (var i=0; i < aChars.length; i++)
    {
        for (var j=bStart; j < bChars.length; j++)
        {
            if(aChars[i] == bChars[j])
            {
                matches.push(aChars[i]);
                bStart = j;
                break;
            }
        }
    }

    return matches.length;
}

compare('abcdef', 'abcdf'); // returns 5
compare('abcdef', 'fedcba'); // returns 1

基本上我从字符串 A 的位置 0 和字符串 B 的位置 0 开始。当找到匹配项时,我更改搜索字符串 B 的起始位置,以便它跳过上一节。

I haven't fully tested it, but this seems to be working (in JavaScript) for your test cases:

function compare(a, b)
{
    var aChars = a.split('');
    var bChars = b.split('');

    var matches = [];
    var bStart = 0;

    for (var i=0; i < aChars.length; i++)
    {
        for (var j=bStart; j < bChars.length; j++)
        {
            if(aChars[i] == bChars[j])
            {
                matches.push(aChars[i]);
                bStart = j;
                break;
            }
        }
    }

    return matches.length;
}

compare('abcdef', 'abcdf'); // returns 5
compare('abcdef', 'fedcba'); // returns 1

Basically I'm starting at position 0 for string A and position 0 for string B. When a match is found, I change the start position for searching string B so that it skips the previous section.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文