查找列表中最长项目的长度的最有效方法是什么?

发布于 2024-07-14 08:21:10 字数 1147 浏览 5 评论 0原文

给定一个不同长度的单词列表,找到任何单词的最大长度的最佳方法是什么?

例如,下面应该返回 6

findMaxLen("a,set,of,random,words")


当然,这样做相当简单...

<cffunction name="findMaxLen" returntype="Numeric">
    <cfset var CurMax = 0 />
    <cfset var CurItem = 0 />
    <cfloop index="CurItem" list="#Arguments[1]#">
        <cfif Len(CurItem) GT CurMax >
            <cfset CurMax = Len(CurItem)/>
        </cfif>
    </cfloop>
    <cfreturn CurMax />
</cffunction>


或者,稍微短一点...

<cffunction name="findMaxLen" returntype="Numeric">
    <cfset var CurMax = 0 />
    <cfset var CurItem = 0 />
    <cfloop index="CurItem" list="#Arguments[1]#">
        <cfset CurMax = Max( CurMax , Len(CurItem) ) />
    </cfloop>
    <cfreturn CurMax />
</cffunction>


但是有没有更好的方法 - 更有效的方法?

也许是一些 Java 方法? 转换为数组并按项目长度排序? 计算逗号之间最大的差距?


实际上,上述两个示例中的任何一个都可以很好地满足我当前的需求,并且这不适用于对性能至关重要的东西,因此我不需要对此的答案,但我认为看看人们可能想出什么仍然很有趣......

Given a list of assorted length words, what is the best way to find the maximum length of any words?

For example, the following should return 6

findMaxLen("a,set,of,random,words")

Of course, it's fairly trivial to do this...

<cffunction name="findMaxLen" returntype="Numeric">
    <cfset var CurMax = 0 />
    <cfset var CurItem = 0 />
    <cfloop index="CurItem" list="#Arguments[1]#">
        <cfif Len(CurItem) GT CurMax >
            <cfset CurMax = Len(CurItem)/>
        </cfif>
    </cfloop>
    <cfreturn CurMax />
</cffunction>

Or, a little shorter...

<cffunction name="findMaxLen" returntype="Numeric">
    <cfset var CurMax = 0 />
    <cfset var CurItem = 0 />
    <cfloop index="CurItem" list="#Arguments[1]#">
        <cfset CurMax = Max( CurMax , Len(CurItem) ) />
    </cfloop>
    <cfreturn CurMax />
</cffunction>

But is there a better way - something more efficient?

Perhaps some Java method? Converting to array and sorting by item length? Counting the biggest gap between commas?

In practical terms, either of the above two examples will work fine for my current need, and this isn't for something that is performance critical, so I don't need an answer to this, but I thought it would still be interesting to see what people might come up with...

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

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

发布评论

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

评论(14

牛↙奶布丁 2024-07-21 08:21:11

J 中,

假设盒装字符串列表(L):

{.\:~>#&.>L

使用 CSV 文件的示例:

{.\:~;>#&.>readcsv'test.csv'

In J

Assume list of boxed strings(L):

{.\:~>#&.>L

An example using a CSV file:

{.\:~;>#&.>readcsv'test.csv'
失与倦" 2024-07-21 08:21:11

在 scala 中(55 个字符):

",set,of,random,words".split(",").:\(0)(_.length max _)

In scala (55 chars):

",set,of,random,words".split(",").:\(0)(_.length max _)
浅忆 2024-07-21 08:21:11

Clojure:49 字节。

(def l #(reduce max(for[x(.split%%2)](count x))))

清晰版本:

(defn longest [astr sep]
  (reduce max
    (for [word (.split astr sep)]
      (count word))))

我仍在学习这门语言,所以我很想听听任何改进它的方法。

Clojure: 49 bytes.

(def l #(reduce max(for[x(.split%%2)](count x))))

Legible version:

(defn longest [astr sep]
  (reduce max
    (for [word (.split astr sep)]
      (count word))))

I'm still learning the language, so I'd love to hear any ways to improve it.

趁微风不噪 2024-07-21 08:21:11

我面前没有Python,所以我无法检查它是否有效,但是......

def maxlen(x):
    return len(sorted(x.split(), key=lambda y: len(y))[1])

应该可以解决问题。

I don't have Python in front of me so I can't check this works, but...

def maxlen(x):
    return len(sorted(x.split(), key=lambda y: len(y))[1])

Should do the trick.

糖果控 2024-07-21 08:21:11

这不是最简单的吗?

<cffunction name="findMaxLen" returntype="Numeric">
    <cfset longest = 0>
    <cfloop list="#Arguments[1]#" index="w">
        <cfif len(w) gt longest>
            <cfset longest = len(w)>
        </cfif>
    </cfloop>
    <cfreturn longest>
</cffunction>

Wouldn't this be simplest?

<cffunction name="findMaxLen" returntype="Numeric">
    <cfset longest = 0>
    <cfloop list="#Arguments[1]#" index="w">
        <cfif len(w) gt longest>
            <cfset longest = len(w)>
        </cfif>
    </cfloop>
    <cfreturn longest>
</cffunction>
青萝楚歌 2024-07-21 08:21:10

计算逗号之间的距离。

我认为没有什么能比这更快了; 它的复杂度为O(n),并且您必须至少查看每个字符一次(看看它是否是逗号)。

int FindLongestWord(char* str)
{
   char* lastComma = str - 1;
   int longest = 0;
   int length;
   char* pCheckChar;

   for(pCheckChar = str; *pCheckChar; pCheckChar++)
   {
      if(*pCheckChar == ',')
      {
         length = pCheckChar - lastComma - 1;
         if(length > longest)
         {
            longest = length;
         }

         lastComma = pCheckChar;
      }
   }

   // Check to see if the last word is the longest
   length = pCheckChar - lastComma - 1;
   if(length > longest)
   {
      longest = length;
   }

   return longest;
}

或者我想你可以说

"a,set,of,random,words".Split(',').Max(w=>w.Length);

我们是否在玩游戏......;]

Count the distance between commas.

I don't think anything could be faster than that; it's O(n), and you have to look at each character at least once anyway (to see if it's a comma).

int FindLongestWord(char* str)
{
   char* lastComma = str - 1;
   int longest = 0;
   int length;
   char* pCheckChar;

   for(pCheckChar = str; *pCheckChar; pCheckChar++)
   {
      if(*pCheckChar == ',')
      {
         length = pCheckChar - lastComma - 1;
         if(length > longest)
         {
            longest = length;
         }

         lastComma = pCheckChar;
      }
   }

   // Check to see if the last word is the longest
   length = pCheckChar - lastComma - 1;
   if(length > longest)
   {
      longest = length;
   }

   return longest;
}

or I suppose you could just say

"a,set,of,random,words".Split(',').Max(w=>w.Length);

if we're playing games... ;]

屋顶上的小猫咪 2024-07-21 08:21:10

在 Perl 中(假设我们有一个变量 $max 来存储答案):

(length $1 > $max) && ($max = length $1) while "a,set,of,random,words" =~ /(\w+)/g;

Or:

(length $_ > $max) && ($max = length $_) foreach split /,/, "a,set,of,random,words";

Or:

$max = length((sort { length $b <=> length $a } split /,/, "a,set,of,random,words")[0]);

TMTOWTDI,毕竟。

编辑:我忘记了核心模块!

use List::Util 'reduce';
$max = length reduce { length $a > length $b ? $a : $b } split /,/, "a,set,of,random,words";

...不知怎的,它比其他的更长。 那好吧!

编辑2:我刚刚记得map()

use List::Util 'max';
$max = max map length, split /,/, "a,set,of,random,words";

更像是我正在寻找的东西。

编辑3:为了完整性:

($max) = sort { $b <=> $a } map length, split /,/, "a,set,of,random,words";

In Perl (assuming we have a variable $max in which the answer is to be stored):

(length $1 > $max) && ($max = length $1) while "a,set,of,random,words" =~ /(\w+)/g;

Or:

(length $_ > $max) && ($max = length $_) foreach split /,/, "a,set,of,random,words";

Or:

$max = length((sort { length $b <=> length $a } split /,/, "a,set,of,random,words")[0]);

TMTOWTDI, after all.

EDIT: I forgot about the Core Modules!

use List::Util 'reduce';
$max = length reduce { length $a > length $b ? $a : $b } split /,/, "a,set,of,random,words";

...which somehow manages to be longer than the other ones. Oh well!

EDIT 2: I just remembered map():

use List::Util 'max';
$max = max map length, split /,/, "a,set,of,random,words";

That's more like what I'm looking for.

EDIT 3: And just for completeness:

($max) = sort { $b <=> $a } map length, split /,/, "a,set,of,random,words";
怪我太投入 2024-07-21 08:21:10

看到有一个 code-golf 标签,这里有 52 个 C# 字符

"a,set,of,random,words".Split(',').Max(w=>w.Length);

Seeing as there's a code-golf tag, here's 52 characters in C#

"a,set,of,random,words".Split(',').Max(w=>w.Length);
潦草背影 2024-07-21 08:21:10

这是“短”CFML 方式 - 72 个字符...

Len(ArrayMax("a,set,of,random,words".replaceAll('[^,]','1').split(',')))

另一个版本,78 个字符,但处理巨大的字符串(请参阅评论)...

Len(ListLast(ListSort("a,set,of,random,words".replaceAll('[^,]','1'),'text')))

And here's the 'short' CFML way - 72 chars...

Len(ArrayMax("a,set,of,random,words".replaceAll('[^,]','1').split(',')))

Another version, 78 chars but handles huge strings (see comments)...

Len(ListLast(ListSort("a,set,of,random,words".replaceAll('[^,]','1'),'text')))
恏ㄋ傷疤忘ㄋ疼 2024-07-21 08:21:10

我确实看到了高尔夫标签代码 - 这是 Python 中的 54 个字符:

len(max("a,set,of,random,words".split(","), key=len))

I did see the code golf tag - here is 54 characters in Python:

len(max("a,set,of,random,words".split(","), key=len))
踏月而来 2024-07-21 08:21:10

在java中没有字符串额外的函数。 (只是一个伪链表:P)在开始时将 max 设为 0

   int find(LinkedList strings, int max) {
      int i;
      String s=(String)strings.element();
      for(i=0;s.charAt(i)!='\0';i++);
      if(strings.hasNext())
         return find(strings.Next(),(i>max?i:max));
      return max;
    }

编辑:刚刚注意到现在它给出了一个单词字符串而不是字符串列表,好吧,不要介意留在这里相同:)

In java without string extra functions. (just a pseudo linked list :P) Give max as 0 in the begining

   int find(LinkedList strings, int max) {
      int i;
      String s=(String)strings.element();
      for(i=0;s.charAt(i)!='\0';i++);
      if(strings.hasNext())
         return find(strings.Next(),(i>max?i:max));
      return max;
    }

Edit: Just noticed now it's given a String of words not a list of strings, well never mind stays here the same :)

绮筵 2024-07-21 08:21:10

如果您不担心可读性...;)

String longest(String...ss){String _="";for(String s:ss)if(_.length()<s.length())_=s;return _;}

If you are not worried about readability... ;)

String longest(String...ss){String _="";for(String s:ss)if(_.length()<s.length())_=s;return _;}
独守阴晴ぅ圆缺 2024-07-21 08:21:10

我想这取决于高效意味着什么。 如果它意味着编写的代码中最少的字符数,那是一回事。 如果这意味着最少的内存或最快的执行,那就是另一回事了。

为了最快执行,我将采用循环。

i guess it depends on what efficient means. if it means the least amount of characters in the code written, that is one thing. if it means, least amount of memory or fastest executing, that is another.

for fastest executing i'll take the loop.

写给空气的情书 2024-07-21 08:21:10

在VC++中

int findMaxLen(const char *s)
{
    const char c = ',';
    int a = 0, b = 0;
    while(*s)
    {
        while(*s && *s++ != c)b++;
        if(b > a)a=b;
        b = 0;
    }
    return a;
}

in vc++

int findMaxLen(const char *s)
{
    const char c = ',';
    int a = 0, b = 0;
    while(*s)
    {
        while(*s && *s++ != c)b++;
        if(b > a)a=b;
        b = 0;
    }
    return a;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文