开发者

Find the max length of continuous white space in an array

There is a array filled with char elements, can you suggest a most efficient way to find the max length of continuous white spac开发者_StackOverflow社区e?


Scan the array from left to right, keep a count of white space. When you reach a non-whitespace character, check that count against the current max; if it's higher, it becomes the new max. Skip forwards this max number in the array - if it is not whitespace you know the interval cannot contain the max whitespace. Otherwise search backwards to where whitespace started - find that set your count and continue from where you had previously skipped to.

I believe worst case performance of this would be O(n) and best case would be O(sqrt(n)) for the case where there is a sqrt(n) start of whitespace followed by non-whitespace on every skip point (causing repeated skipping to the end of the array).


scan the array left to right, keep a count of white space. When you reach a non-whitespace character, check that count against the current max; if it's higher, it becomes the new max. Set the count back to zero, continue scanning. This is O(n) and you can't really do better because you have to touch each element at least once.


You need not to scan whole array. Just keep checking remaining data also if it is less than current max white spaces, then stop the scanning.

example

1 space space 2 space space scape 3 4

here after coming to 3 u know that only 2 elements are left and those are less than ur current max spaces (3).


A char array is nothing but a string. so basically you are trying to find max length of continuous space. Assuming your char array is single dimensional i.e. single string and not array of strings.

int maxSpaceLength = 0;
int currentSpaceCount = 0;

for (int i = 0; i < charArray.length; i++) {
    if (charArray[i] == ' ') {
        currentSpaceCount++;
    } else {
        if(maxSpaceLength < currentSpaceCount)
            maxSpaceLength = currentSpaceCount;
        currentSpaceCount = 0;
    }
}

return maxSpaceLength;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜