首页 > 其他 > 详细

三目运算的学习与应用

时间:2021-04-04 01:11:29      阅读:29      评论:0      收藏:0      [点我收藏+]

三目运算

三目运算百度百科

三目运算符,又称条件运算符,是计算机语言(c,c++,java等)的重要组成部分。它是唯一有3个操作数的运算符,有时又称为三元运算符。一般来说,三目运算符的结合性是右结合的。

定义

对于条件表达式b ? x : y,先计算条件b,然后进行判断。
如果b的值为true,计算x的值,运算结果为x的值;否则,计算y的值,运算结果为y的值。
一个条件表达式绝不会既计算x,又计算y。

条件运算符是右结合的,也就是说,从右向左分组计算。例如,a ? b : c ? d : e将按a ? b : (c ? d : e)执行。

? : ; "?"运算符的含义是:
先求表达式1的值,如果为真,则执行表达式2,并返回表达式2的结果;
如果表达式1的值为假,则执行表达式3,并返回表达式3的结果。

可以理解为条件 ? 结果1 : 结果2 里面的?号是格式要求。也可以理解为条件是否成立,条件成立为结果1,否则为结果2。

注意:在C语言中,结果1 和 结果2的类型必须一致。

一般来说,三目运算符的结合性是右结合的
但是这点在ANSI C中并没有明确规定
所以它的执行顺序有时是由编译器决定的

a?b:c的含义

if(a) {
    return b;
} else {
    return c;
}

LeetCode的1576题

替换所有的问号-难度简单28

题目的优秀解法

    public String modifyString(String s) {
        char[] chars = s.toCharArray();

        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == ‘?‘) {
                //前面一个字符  如果当前是第0个的话 字符就为‘ ’
                char ahead = i == 0 ? ‘ ‘ : chars[i - 1];
                //后面一个字符  如果当前是最后一个的话 字符就为‘ ’
                char behind  = i == chars.length - 1 ? ‘ ‘ : chars[i + 1];
                //从a开始比较  如果等于前面或者后面的话 就+1
                char temp = ‘a‘;
                while (temp == ahead || temp == behind ) {
                    temp++;
                }
                //找到目标字符后 做替换
                chars[i] = temp;
            }
        }
        return new String(chars);
    }

作者:JayceonDu
链接:https://leetcode-cn.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/solution/jian-dan-de-ji-xing-dai-ma-by-jayceondu/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

博主为了练习范围随机数与数组字符串转换而乱写的废解法,不要学

    public String modifyString(String s) {
        if (s.length() < 2) {
            if (s.equals("?"))
                s = "a";
            return s;
        }

        Random random = new Random();
        int r = random.nextInt(26)+97; //范围随机数
        char beforeVal = ‘/‘;
        char[] cArr = s.toCharArray();
        for (int i = 0; i < cArr.length; i++) {

            if (cArr[i] == ‘?‘) {
                if (beforeVal == ‘/‘) {
                    while (r == cArr[i+1]) {
                        r = random.nextInt(26)+97;
                    }
                    cArr[i] = (char)r;
                } else if ((i+1)<cArr.length) {
                    while (r == beforeVal || r == cArr[i+1]) {
                        r = random.nextInt(26)+97;
                    }
                    cArr[i] = (char)r;
                } else {
                    while (r == beforeVal) {
                        r = random.nextInt(26)+97;
                    }
                    cArr[i] = (char)r;  //int转char的强制转型
                }
            }
            beforeVal = cArr[i];
        }

        return String.copyValueOf(cArr); // 等效于new String(cArr);
    }

关于String类copyValueof(char[])的实现方式

    /**
     * Equivalent to {@link #valueOf(char[])}.
     *
     * @param   data   the character array.
     * @return  a {@code String} that contains the characters of the
     *          character array.
     */
    public static String copyValueOf(char data[]) {
        return new String(data);
    }

这个String(char[] value)的构造方法,其实到这里也没啥可继续的了。。。

    /**
     * Allocates a new {@code String} so that it represents the sequence of
     * characters currently contained in the character array argument. The
     * contents of the character array are copied; subsequent modification of
     * the character array does not affect the newly created string.
     *
     * @param  value
     *         The initial value of the string
     */
    public String(char value[]) {   //竟然是这种声明数组的写法,蛮有意思的,不是不推荐的么?
        this.value = Arrays.copyOf(value, value.length);
    }

Arrays类的copyof(char[] value, int length)方法,突然发现还可以看看,就当丰富自己的认识

    /**
     * Copies the specified array, truncating or padding with null characters (if necessary)
     * so the copy has the specified length.  For all indices that are valid
     * in both the original array and the copy, the two arrays will contain
     * identical values.  For any indices that are valid in the copy but not
     * the original, the copy will contain <tt>‘\\u000‘</tt>.  Such indices
     * will exist if and only if the specified length is greater than that of
     * the original array.
     *
     * @param original the array to be copied
     * @param newLength the length of the copy to be returned
     * @return a copy of the original array, truncated or padded with null characters
     *     to obtain the specified length
     * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
     * @throws NullPointerException if <tt>original</tt> is null
     * @since 1.6
     */
    public static char[] copyOf(char[] original, int newLength) {
        char[] copy = new char[newLength];
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength)); // System类了。。别问,native了呗
        return copy;
    }

System类的arraycopy方法,纯当英文学习吧,现阶段不深究了,等博主超进化回来。

    /**
     * Copies an array from the specified source array, beginning at the
     * specified position, to the specified position of the destination array.
     * A subsequence of array components are copied from the source
     * array referenced by <code>src</code> to the destination array
     * referenced by <code>dest</code>. The number of components copied is
     * equal to the <code>length</code> argument. The components at
     * positions <code>srcPos</code> through
     * <code>srcPos+length-1</code> in the source array are copied into
     * positions <code>destPos</code> through
     * <code>destPos+length-1</code>, respectively, of the destination
     * array.
     * <p>
     * If the <code>src</code> and <code>dest</code> arguments refer to the
     * same array object, then the copying is performed as if the
     * components at positions <code>srcPos</code> through
     * <code>srcPos+length-1</code> were first copied to a temporary
     * array with <code>length</code> components and then the contents of
     * the temporary array were copied into positions
     * <code>destPos</code> through <code>destPos+length-1</code> of the
     * destination array.
     * <p>
     * If <code>dest</code> is <code>null</code>, then a
     * <code>NullPointerException</code> is thrown.
     * <p>
     * If <code>src</code> is <code>null</code>, then a
     * <code>NullPointerException</code> is thrown and the destination
     * array is not modified.
     * <p>
     * Otherwise, if any of the following is true, an
     * <code>ArrayStoreException</code> is thrown and the destination is
     * not modified:
     * <ul>
     * <li>The <code>src</code> argument refers to an object that is not an
     *     array.
     * <li>The <code>dest</code> argument refers to an object that is not an
     *     array.
     * <li>The <code>src</code> argument and <code>dest</code> argument refer
     *     to arrays whose component types are different primitive types.
     * <li>The <code>src</code> argument refers to an array with a primitive
     *    component type and the <code>dest</code> argument refers to an array
     *     with a reference component type.
     * <li>The <code>src</code> argument refers to an array with a reference
     *    component type and the <code>dest</code> argument refers to an array
     *     with a primitive component type.
     * </ul>
     * <p>
     * Otherwise, if any of the following is true, an
     * <code>IndexOutOfBoundsException</code> is
     * thrown and the destination is not modified:
     * <ul>
     * <li>The <code>srcPos</code> argument is negative.
     * <li>The <code>destPos</code> argument is negative.
     * <li>The <code>length</code> argument is negative.
     * <li><code>srcPos+length</code> is greater than
     *     <code>src.length</code>, the length of the source array.
     * <li><code>destPos+length</code> is greater than
     *     <code>dest.length</code>, the length of the destination array.
     * </ul>
     * <p>
     * Otherwise, if any actual component of the source array from
     * position <code>srcPos</code> through
     * <code>srcPos+length-1</code> cannot be converted to the component
     * type of the destination array by assignment conversion, an
     * <code>ArrayStoreException</code> is thrown. In this case, let
     * <b><i>k</i></b> be the smallest nonnegative integer less than
     * length such that <code>src[srcPos+</code><i>k</i><code>]</code>
     * cannot be converted to the component type of the destination
     * array; when the exception is thrown, source array components from
     * positions <code>srcPos</code> through
     * <code>srcPos+</code><i>k</i><code>-1</code>
     * will already have been copied to destination array positions
     * <code>destPos</code> through
     * <code>destPos+</code><i>k</I><code>-1</code> and no other
     * positions of the destination array will have been modified.
     * (Because of the restrictions already itemized, this
     * paragraph effectively applies only to the situation where both
     * arrays have component types that are reference types.)
     *
     * @param      src      the source array.
     * @param      srcPos   starting position in the source array.
     * @param      dest     the destination array.
     * @param      destPos  starting position in the destination data.
     * @param      length   the number of array elements to be copied.
     * @exception  IndexOutOfBoundsException  if copying would cause
     *               access of data outside array bounds.
     * @exception  ArrayStoreException  if an element in the <code>src</code>
     *               array could not be stored into the <code>dest</code> array
     *               because of a type mismatch.
     * @exception  NullPointerException if either <code>src</code> or
     *               <code>dest</code> is <code>null</code>.
     */
    public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

三目运算的学习与应用

原文:https://www.cnblogs.com/boziyouning/p/14615409.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!